【问题标题】:BinaryFileResponse : The content cannot be set on a BinaryFileResponse instanceBinaryFileResponse :无法在 BinaryFileResponse 实例上设置内容
【发布时间】:2015-01-29 13:49:54
【问题描述】:

我尝试从控制器下载文件(此处为附件)

这是我的代码:

/**
 * @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()

返回绝对路径(正确)

最后,我得到这个错误=> 无法在 BinaryFileResponse 实例上设置内容。

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

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

此外,如果我删除 setContent 方法中的 if 语句,一切都会像魅力一样工作。 (但这不是最好的做法)

感谢您的帮助

【问题讨论】:

    标签: symfony


    【解决方案1】:

    我已经测试了您的代码,它对我有用。尝试用这个替换 return 语句:

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

    【讨论】:

    • 感谢您的帮助,这对我不起作用,我使用 Symfony 2.4 也许错误来自这里?
    • 我正在使用 2.6 并尝试 return BinaryFileResponse::create(__FILE__);return new BinaryFileResponse(__FILE__);,成功触发控制器文件本身的下载。试试看,以防万一文件路径有问题。除此之外,我建议升级 symfony 看看是否能解决问题,因为代码看起来不错。
    • 对不起,我来晚了,FILE 给我同样的错误。我将尝试使用最新的 symfony 版本,再次感谢您的帮助
    • 嗨,我已经解决了我的问题,有一个监听器可以修改我的响应。 (错误隐藏在堆栈跟踪中)
    • 我知道您显示的代码是正确的!很高兴你最终解决了这个问题:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多