Symfony2:如何显示/下载BLOB字段 [英] Symfony2: How to display/download a BLOB field
问题描述
对于我的客户,我必须对一些各种文件使用blob存储.
For my client I have to use blob storage for some various files.
因此,我创建了一个独立的捆绑包,其Blob类扩展了Doctrine \ DBAL \ Types \ Type. 并在bundle类中具有启动功能.
So I have created a independent bundle with a Blob class extends Doctrine\DBAL\Types\Type. and with a boot function in the bundle class.
那很好,我可以在数据库中写入Blob数据.
That works pretty fine I can write in the database Blob datas.
但是在:/
我有:
public function downloadAction($id) {
$em = $this->getDoctrine()->getManager();
/* @var $entity Document */
$entity = $em->getRepository('Lille3SapBundle:Document')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Document entity.');
}
$file = $entity->getFichier();
$response = new \Symfony\Component\HttpFoundation\Response($file, 200, array(
'Content-Type' => 'application/octet-stream',
'Content-Length' => sizeof($file),
'Content-Disposition' => 'attachment; filename="'.$entity->getNomDocument().'"',
));
return $response;
}
,但我有一个例外: 响应内容必须是实现__toString()的字符串或对象,并给出"resource".
and I have got an Exception: The Response content must be a string or object implementing __toString(), "resource" given.
实际上, $ file 值不是预期的BLOB,而是类似 Resource id#123
in fact, the $file values is not the expected BLOB but something like Resource id #123
->我已经检查了blob数据字段的值,并且它们在数据库中没问题
-> I have check blob data fields values, and they are ok in the database
所以我该如何在控制器中强制使用blob行而不是 Resource id#111
So how can I force in the controller to have the blob row and not a Resource id #111
推荐答案
您仍然可以按照最初的计划将 BLOB 字段用于数据库中的字段.
You can still use BLOB field for your field in DB as you initially planned.
在 createAction 中照常存储数据(没有base64_encode()):
In createAction store data as usual (with no base64_encode()):
$stream = fopen($entity->getFichier(),'rb');
$entity->setFichier(stream_get_contents($stream));
和 downloadAction 中只需使用:
$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;
说明:
BLOB 字段被视为没有__toString()实现的 resource 变量.
BLOB fields are treated as resource variable which have no __toString() implementation.
gettype($file) -> "resource"
get_resource_type($file) -> "stream"
stream_get_contents($ file)在这里起到了神奇的作用:从资源变量中获取 STRING 内容.
stream_get_contents($file) makes the magic here: gets STRING content from resource variable.
这篇关于Symfony2:如何显示/下载BLOB字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!