Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2: Upload file and save as blob

I'm trying to save images in database with forms and Doctrine. In my entity, I've done this:

/**
 * @ORM\Column(name="photo", type="blob", nullable=true)
 */
private $photo;

private $file;


/**
 * @ORM\PrePersist()
 * @ORM\PreUpdate()
 */
public function upload()
{
    if (null === $this->file) {
        return;
    }

    $this->setPhoto(file_get_contents($this->getFile()));
}

And I've also added this in my form type:

->add('file', 'file')

But I'm getting this error when I upload a file:

Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed

like image 326
Florentin Avatar asked Aug 10 '14 13:08

Florentin


2 Answers

You have to save the image file content as binary

public function upload()
{
    if (null === $this->file) {
        return;
    }

    //$strm = fopen($this->file,'rb');
    $strm = fopen($this->file->getRealPath(),'rb');
    $this->setPhoto(stream_get_contents($strm));
}

UploadedFile is a class that extends File that extends SplFileInfo

SplFileInfo has the function getRealPath() that returns the path of the temp filename.

This is just in case that you don't want to upload the file to the server, to do that follow these steps.

like image 57
tttony Avatar answered Sep 21 '22 21:09

tttony


The problem is that when Symfony uploads a file it assigns the property that the file is uploaded to an object of type UploadedFile.

So $file is of type Symfony\Component\HttpFoundation\File\UploadedFile.

The error message you are getting is telling you that you cannot store an object of that type like that - and really you don't want to do that anyway, you want to pass the file name with path to file_get_contents().

So all you need to do to fix this is to access the location of the file from the object like so:

$this->setPhoto(file_get_contents($this->getFile()->getPathname()));

Note the call to getPathname() added to the end of the chain.

Also, I would definitely keep file_get_contents() because the documentation states that:

file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

like image 45
Bananaapple Avatar answered Sep 17 '22 21:09

Bananaapple