Symfony 2:上传文件并保存为blob

The*_*ow_ 9 php doctrine blob symfony

我正在尝试使用表单和Doctrine在数据库中保存图像.在我的实体中,我做到了这一点:

/**
 * @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()));
}
Run Code Online (Sandbox Code Playgroud)

我还在我的表单类型中添加了这个:

->add('file', 'file')
Run Code Online (Sandbox Code Playgroud)

但是当我上传文件时,我收到此错误:

不允许序列化'Symfony\Component\HttpFoundation\File\UploadedFile'

ttt*_*ony 8

您必须将图像文件内容保存为二进制文件

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));
}
Run Code Online (Sandbox Code Playgroud)

UploadedFile是一个扩展的一类File,其延伸SplFileInfo

SplFileInfo具有getRealPath()返回临时文件名路径的函数.

这是为了您不想将文件上传到服务器,为此请按照这些步骤操作.