gpt4 book ai didi

Symfony2 : How to display/download a BLOB field

转载 作者:行者123 更新时间:2023-12-02 04:39:44 24 4
gpt4 key购买 nike

对于我的客户,我必须使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com