Symfony2:如何显示/下载BLOB字段

sai*_*ist 15 blob symfony

对于我的客户端,我必须使用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;
}
Run Code Online (Sandbox Code Playgroud)

我有一个例外:响应内容必须是一个字符串或对象,实现__toString(),给定"资源".

实际上,$ file值不是预期的BLOB,而是类似于资源ID#123

- >我检查了blob数据字段值,它们在数据库中没问题

那么我如何强制控制器中的blob行而不是资源ID#111

小智 26

您仍然可以按照最初计划在数据库中为您的字段使用BLOB字段.

createAction中像往常一样存储数据(没有base64_encode()):

$stream = fopen($entity->getFichier(),'rb');
$entity->setFichier(stream_get_contents($stream));
Run Code Online (Sandbox Code Playgroud)

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

说明:

BLOB字段被视为没有__toString()实现的资源变量.

gettype($file) -> "resource"
get_resource_type($file) -> "stream"
Run Code Online (Sandbox Code Playgroud)

stream_get_contents($ file)在这里发挥作用:从资源变量中获取STRING内容.

  • 如果您直接从Doctrine实体的属性获取流,请不要忘记调用`rewind($ entity-> getFichier());`. (4认同)

sai*_*ist 1

好吧,我有一个(非常丑陋的)解决方案:

首先:我将文档实体的文件属性的数据类型blob更改为文本。

其次:在 createAction 中我更改了 setFichier 调用:

$stream = fopen($entity->getFichier(),'rb');
$entity->setFichier(base64_encode(stream_get_contents($stream)));
Run Code Online (Sandbox Code Playgroud)

第三:在 downloadAction 中,我对文本 base64 文本字段进行解码:

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

现在我可以坚持并以 blob 方式下载文件......