Symfony2: How to display/download a BLOB field

£可爱£侵袭症+ 提交于 2019-11-29 01:28:57

You can still use BLOB field for your field in DB as you initially planned.

In createAction store data as usual (with no base64_encode()):

$stream = fopen($entity->getFichier(),'rb');
$entity->setFichier(stream_get_contents($stream));

and in downloadAction just use:

$file = $entity->getFichier();
$response = new \Symfony\Component\HttpFoundation\Response(stream_get_contents($file), 200, array(
    'Content-Type' => 'application/octet-stream',
    'Content-Length' => sizeof($file),
    'Content-Disposition' => 'attachment; filename="'.$entity->getNomDocument().'"',
));

return $response;

Explanation:

BLOB fields are treated as resource variable which have no __toString() implementation.

gettype($file) -> "resource"
get_resource_type($file) -> "stream"

stream_get_contents($file) makes the magic here: gets STRING content from resource variable.

Okay, I have got a (very uggly) solution:

Firstly: I changed the data type blob to text for the file attribute of Document entity.

Secondly: in createAction I've changed the setFichier call:

$stream = fopen($entity->getFichier(),'rb');
$entity->setFichier(base64_encode(stream_get_contents($stream)));

Thirdly: in downloadAction, I decode the text base64 text field:

$file = $entity->getFichier();              
$response = new \Symfony\Component\HttpFoundation\Response(base64_decode($file), 200, array(
        'Content-Type' => 'application/octet-stream',
        'Content-Length' => sizeof($file),
        'Content-Disposition' => 'attachment; filename="'.$entity->getNomDocument().'"',
));

return $response;

And now I can persist and download files as blob way...

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!