symfony - 二进制文件响应 : The content cannot be set on a BinaryFileResponse instance

标签 symfony

我尝试从 Controller 下载文件(此处为附件)

这是我的代码:

/**
 * @param Request    $request
 * @param Attachment $attachment
 *
 * @Route("/message/{thread_id}/download/{attachment_id}", name="faq_download_attachment")
 * @ParamConverter("attachment", options={"id" = "attachment_id"})
 *
 * @return BinaryFileResponse
 *
 * @throws \Symfony\Component\Filesystem\Exception\FileNotFoundException
 */

public function downloadFiletAction(Request $request, Attachment $attachment)
{
    $mountManager = $this->get('oneup_flysystem.mount_manager');
    $fileSystem = $mountManager->getFilesystem('faq');
    return new BinaryFileResponse($fileSystem->getAdapter()->getPathPrefix() . $attachment->getFilename());
}

这段代码:

$fileSystem->getAdapter()->getPathPrefix() . $attachment->getFilename()

返回绝对路径(这是正确的)

enter image description here 最后,我收到这个错误=> 无法在 BinaryFileResponse 实例上设置内容。

似乎当我实例化 BinaryFileResponse 时,symfony 将其内容设置为 NULL (这就是我想要的),但是当我放置 return 语句时。我的内容被替换为空字符串,这是一件坏事,因为 BinaryFileResponse 的以下函数抛出异常。

public function setContent($content)
{
    if (null !== $content) {
        throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
    }
}

此外,如果我删除 setContent 方法中的 if 语句,一切都会变得非常顺利。 (但这不是最好的做法)

感谢您的帮助

最佳答案

我已经测试了你的代码,它对我有用。尝试用以下内容替换 return 语句:

return BinaryFileResponse::create($fileSystem->getAdapter()->getPathPrefix() . $attachment->getFilename());

关于symfony - 二进制文件响应 : The content cannot be set on a BinaryFileResponse instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28216381/

相关文章:

entity-framework - 使用 KnpLabs 的 SoftDeletable 时强制删除学说实体

php - 异常Eventlistener无法捕获RabbitMQ使用者的异常

laravel - 如何像格式化数组一样使用 monolog 记录多行条目?

php - 选择最后一个和下一个记录时 Symfony DQL 语法错误

php - Symfony:在 Doctrine Entity 方法中使用返回类型提示的表单问题

Symfony2 FosUserBundle 和 SonataUserBundle : overriding entities?

php - Symfony2-表单错误(对于整个表单,不是单个字段)不显示

php - 使用 FOSRestBundle REST API 设置注册 FOSUserBundle

php - 如何删除列的字段前缀

javascript - 获取输入的动态值 JQuery + Twig