How can I upload file with VichUploaderBundle without form?
I have file in some directory (for example 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've got this error:
The file "temp_file.jpg" was not uploaded due to an unknown error.
I need to upload file from remote url. So I upload file to tmp
direcotry (with curl) and then I keep trying to inject it to VichUploadBundle (as you can see above).
Accepted answer is not correct (anymore?). According with the usage documentation
you can indeed manually upload a File
without using Symfony's Form Component:
/**
* 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');
}
}
You should use Symfony\Component\HttpFoundation\File\UploadedFile
instead of File
:
$file = new UploadedFile($filename, $filename, null, filesize($filename), false, true);
VichUploaderBundle
will handle this object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With