How can I upload a file from VichUploaderBundle without a form?
I have a file in some directory (e.g. web/media/tmp/temp_file.jpg )
web/media/tmp/temp_file.jpg
If I try this:
$file = new UploadedFile($path, $filename); $image = new Image(); $image->setImageFile($file); $em->persist($image); $em->flush();
I have this error:
The file "temp_file.jpg" was not loaded due to an unknown error.
I need to download a file from a remote url. So I upload the file to tmp direcotry (with curl) and then keep trying to paste it into VichUploadBundle (as you can see above).
tmp
Short answer: VichUploaderBundle does not support downloading files without using the Symfony Form component.
VichUploaderBundle
In this case, you do not need to download, you need to download. And this is not what VichUploaderBundle needs to do.
The accepted answer is incorrect (more?). According to the documentation, you really can manually download File without using the Symfony Form Component:
File
/** * If manually uploading a file (ie not using Symfony Form) ensure an instance * of 'UploadedFile' is injected into this setter to trigger the update. If this * bundle 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'); } }
You should use Symfony\Component\HttpFoundation\File\UploadedFile instead of File :
Symfony\Component\HttpFoundation\File\UploadedFile
$file = new UploadedFile($filename, $filename, null, filesize($filename), false, true);
VichUploaderBundle will process this object.