Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: manual file upload with VichUploaderBundle

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

like image 492
Tomas S. Avatar asked Aug 04 '15 14:08

Tomas S.


Video Answer


2 Answers

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');
    }
}
like image 192
TMichel Avatar answered Oct 12 '22 04:10

TMichel


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.

like image 34
Dmitry Avatar answered Oct 12 '22 02:10

Dmitry