Php – Symfony 2: Upload file and save as blob

blobdoctrinePHPsymfony

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

Best Answer

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.

Related Topic