作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
对于我的客户,我必须使用 blob 存储来存储一些不同的文件。
因此,我创建了一个独立的包,其中 Blob 类扩展了 Doctrine\DBAL\Types\Type。并在 bundle 类中具有启动功能。
这工作得很好,我可以在数据库 Blob 数据中写入。
但是我无法下载任何文档:/
我有:
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;
}
我有一个异常(exception):响应内容必须是实现 __toString() 的字符串或对象,给定“资源”。
事实上,$file 值不是预期的 BLOB,而是类似于 Resource id #123
-> 我已经检查了 blob 数据字段值,它们在数据库中没有问题
那么我如何强制 Controller 拥有 blob 行而不是资源 id #111
最佳答案
您仍然可以按照最初计划使用 BLOB 字段作为数据库中的字段。
在createAction中照常存储数据(没有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() 实现的资源变量。
gettype($file) -> "resource"
get_resource_type($file) -> "stream"
stream_get_contents($file) 在这里发挥了魔力:从资源变量中获取 STRING 内容。
关于Symfony2 : How to display/download a BLOB field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15206963/
我是一名优秀的程序员,十分优秀!