Symfony3从控制器发送表单

时间:2017-11-06 15:24:04

标签: php forms api symfony

编辑:

我找到了$ form-> submit()方法并尝试了一下:

file_put_contents(__DIR__ . "/../../../web/uploads/img/tmp.jpeg", file_get_contents($output['images']['show']));

$image = new Image();;

$form = $this->createForm(ImageType::class, $image);

$form->submit( __DIR__ . "/../../../web/uploads/img/tmp.jpeg" );

if ($form->isSubmited() && $form->isValid()) {
    ...
}

但显然这种形式没有效力,因为它没有超越条件

编辑2:我为ImageType禁用了csrf_protection但是它仍然无效,Xdebug告诉我路径无效,但是如果我尝试从同一路径上传相同的图像通过表单它没有问题...

我正在开展一个项目,我有这个Image实体:

class Image
{
    //... Attributes, setters and getters        

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        if (null === $this->file) {
            return;
        }
        $this->url = $this->file->guessExtension();
        $this->alt = $this->file->getClientOriginalName();
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
        if (null === $this->file) {
            return;
        }
        if (null !== $this->tempFilename) {
            $oldFile = $this->getUploadRootDir().'/'.$this->id.'.'.$this->tempFilename;
            if (file_exists($oldFile)) {
                unlink($oldFile);
            }
        }
        $this->file->move(
            $this->getUploadRootDir(),
            $this->id.'.'.$this->url
        );
    }

    /**
     * @param UploadedFile $file
     */
    public function setFile(UploadedFile $file)
    {
        $this->file = $file;
        if (null !== $this->url) {
            $this->tempFilename = $this->url;
            $this->url = null;
            $this->alt = null;
        }
    }
}

当我通过表单从本地文件上传图像时,这非常适用。

但我还需要能够从API下载文件:

file_put_contents(__DIR__ . "/../../../web/uploads/img/tmp.jpeg", file_get_contents($output['images']['show']));

$image = new Image();

$file = new UploadedFile(__DIR__ . "/../../../web/uploads/img/tmp.jpeg", 'tmp.jpeg');

$image->setFile($file);

据我所知,一旦我坚持$ image,preUpload()和upload()都会被调用,但是当我这样做时,我会收到这个错误:

"文件" tmp.jpeg"由于未知错误而未上传。"

这似乎是由$ this-> file-> move()引发的一部分()

我很确定这是因为UploadedFile的isValid()函数只有在文件上传了HTTP并且在move()开始时被调用时才返回true ...

我的问题有解决方法吗?我对Symfony来说还是比较新的(一般来说编码也不多)所以我并不完全确定我的选择是什么。

有没有办法欺骗$ image进入"思考" $ file来自Form?

1 个答案:

答案 0 :(得分:0)

我已经有一段时间专门做了这个,但我相信如果你希望它有效,你必须在构造函数中手动创建一个mimetype(<1}}。

UploadedFile
相关问题