BinaryFileResponse:无法在BinaryFileResponse实例上设置内容

Jay*_*ybe 6 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());
}
Run Code Online (Sandbox Code Playgroud)

这段代码:

$fileSystem->getAdapter()->getPathPrefix() . $attachment->getFilename()
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述 最后,我收到此错误=> 无法在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.');
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,如果我删除setContent方法中的if语句,Everything就像一个魅力.(但这不是最好的事情)

谢谢您的帮助

Jav*_* H. 3

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

return BinaryFileResponse::create($fileSystem->getAdapter()->getPathPrefix() . $attachment->getFilename());
Run Code Online (Sandbox Code Playgroud)

  • 嗨,我已经解决了我的问题,有一个监听器修改了我的响应。(错误隐藏在堆栈跟踪中) (2认同)