Symfony 2: Upload file and save as blob
Asked Answered
K

2

9

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

Kentkenta answered 10/8, 2014 at 13:13 Comment(1)
Please can someone help me ? I succeed to fix the serialization error adding 'mapped' => false to my file field but with that I can't upload even with @tttony answer...Kentkenta
N
9

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.

Nagle answered 10/8, 2014 at 18:10 Comment(3)
Thank you very much for your answer but I tried and it seems not to workKentkenta
Actually, $this->file is an instance of UploadedFileKentkenta
To fix my serialization error I added 'mapped' => false to my field and I succeed once to upload my image but it didn't work again...Kentkenta
W
1

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.

Wariness answered 22/11, 2018 at 11:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.