【问题标题】:Headers not being modified with Response object in Symfony2Symfony2中的响应对象未修改标头
【发布时间】:2012-03-31 20:43:53
【问题描述】:

我正在尝试使用 Symfony 2 将 PDF 返回到浏览器,所以一旦找到该文件,我就会使用:

return new Response(readfile($file_path), 200, array(
'Content-Type' => 'application/pdf'
));

但如果我加载页面,标题不会被修改,内容不会被解释为 pdf...

< HTTP/1.1 200 OK
< Date: Sat, 31 Mar 2012 20:39:20 GMT
< Server: Apache
< X-Powered-By: PHP/5.3.6
< Set-Cookie: PHPSESSID=XXXX; path=/
< Transfer-Encoding: chunked
< Content-Type: text/html

我迷失了这个问题。有什么想法吗?

【问题讨论】:

    标签: symfony


    【解决方案1】:

    readfile 首先执行,并开始将文件发送到客户端。这会触发要生成的标头。然后将readfile的返回值传递给Response。当响应返回给客户端时,PHP 不可能更改标头,因为它们是在 readfile 运行时触发的。

    readfile 替换为file_get_contents

    【讨论】:

    • file_get_contents 的问题在于它将文件加载到内存中,因此不能用于下载大文件。有没有办法将readfile 与 symfony2 一起使用?
    • 我没有看到任何内置的东西来处理这个问题。我还没有尝试过,但看起来你可以创建一个 \Symfony\Component\HttpFoundation\Response 的子类来覆盖 sendContent() 以使用 readfile。默认实现期望您将实际内容传递给类,您的子类可能会获得一个文件名。我发现 getContent() 存在潜在问题,它应该返回实际内容,但如果没有 file_get_contents,这将不是一个选项。
    【解决方案2】:

    您可能还想使用以下内容

    new StreamedResponse(function () use ($file) {
        readfile($file);
    }, 200, array('Content-Type' => 'image/png');
    

    【讨论】:

    • 谢谢,这里是使用声明:use \Symfony\Component\HttpFoundation\StreamedResponse;
    猜你喜欢
    • 1970-01-01
    • 2016-06-12
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    相关资源
    最近更新 更多