Symfony2:使用VichUploaderBundle手动上传文件

Tom*_* S. 6 php symfony vichuploaderbundle

如何在没有表格的情况下使用VichUploaderBundle上传文件?

我在某个目录中有文件(例如web/media/tmp/temp_file.jpg)

如果我试试这个:

$file = new UploadedFile($path, $filename);

$image = new Image();
$image->setImageFile($file);

$em->persist($image);
$em->flush();
Run Code Online (Sandbox Code Playgroud)

我有这个错误:

由于未知错误,未上载文件"temp_file.jpg".

我需要从远程网址上传文件.所以我将文件上传到tmpdirecotry(使用curl),然后我一直尝试将它注入到VichUploadBundle中(如上所示).

TMi*_*hel 9

接受的答案是不正确的(不再?).根据使用文档, 你可以在File不使用Symfony的表单组件的情况下手动上传一个:

/**
 * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
 * of 'UploadedFile' is injected into this setter to trigger the  update. If this
 * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
 * must be able to accept an instance of 'File' as the bundle will inject one here
 * during Doctrine hydration.
 *
 * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
 */
public function setImageFile(File $image = null)
{
    $this->imageFile = $image;

    if ($image) {
        // It is required that at least one field changes if you are using doctrine
        // otherwise the event listeners won't be called and the file is lost
        $this->updatedAt = new \DateTime('now');
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您想“上传”本地存储的文件,`UploadedFile` 对象必须将测试标志设置为 true,例如:将文件从本地目录迁移到 VichUploader 配置的 upload_destination (2认同)

小智 1

简短回答:VichUploaderBundle不支持在不使用 Symfony Form 组件的情况下上传文件。

我需要从远程网址上传文件。因此,我将文件上传到 tmp direcotry(使用curl),然后我继续尝试将其注入到 VichUploadBundle(如上所示)。

在这种情况下,您不需要上传,您需要下载。但这并不是VichUploaderBundle我们的本意。