Home » Php » php – Symfony2: manual file upload with VichUploaderBundle

php – Symfony2: manual file upload with VichUploaderBundle

Posted by: admin July 12, 2020 Leave a comment

Questions:

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).

How to&Answers:

Short answer: VichUploaderBundle does not support uploading files without using Symfony Form component.

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).

In that case, you don’t need to upload, you need to download. And that’s not what VichUploaderBundle is meant to do.

Answer:

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');
    }
}

Answer:

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.