symfony: setHttpHeader() 不起作用,header() 起作用 [英] symfony: setHttpHeader() doesn't work, header() does

查看:78
本文介绍了symfony: setHttpHeader() 不起作用,header() 起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 symfony 中构建了一个简单的操作,它通过 wkhtmltopdf 生成一个 PDF 文件并将其输出到浏览器.

I built a simple action in symfony which generates a PDF-file via wkhtmltopdf and outputs it to the browser.

代码如下:

  $response = $this->getResponse();
  $response->setContentType('application/pdf');
  $response->setHttpHeader('Content-Disposition', "attachment; filename=filename.pdf");
  $response->setHttpHeader('Content-Length', filesize($file));
  $response->sendHttpHeaders();
  $response->setContent(file_get_contents($file));
  return sfView::NONE;

这在我的本地开发环境中运行良好 - 我的浏览器按预期获取标头,显示下载对话.

That works fine in my local development environment - my browser gets the headers as expected, showing the download-dialogue.

现在我更新了我的测试环境,使用 PHP 5.3.5-0.dotdeb.0 运行 Apache 2.2.9-10+lenny9.如果我现在为测试环境调用该 URL,我的浏览器不会获得任何自定义集标头:

Now I updated my testing-environment, running Apache 2.2.9-10+lenny9 with PHP 5.3.5-0.dotdeb.0. If i call that URL now for the testing-environment, my browser don't get any custom set headers:

Date    Mon, 07 Mar 2011 10:34:37 GMT
Server  Apache
Keep-Alive  timeout=15, max=100
Connection  Keep-Alive
Transfer-Encoding   chunked

如果我在操作中通过 header() 手动设置它们,Firebug 会按预期显示标题.有谁知道可能有什么问题?是 symfony 错误,还是 php 或 apache2 配置问题?我不明白.:-/

If I set them manually via header() in my action, Firebug shows the headers as expected. Does anybody know what could be wrong? Is it a symfony bug, or a php or apache2 configuration issue? I don't get it. :-/

提前致谢!

推荐答案

你的问题在这里:

return sfView::NONE;

将其更改为:

return sfView::HEADERS_ONLY;

编辑由于额外的评论而更新.

edit update due to extra comments.

由于您尝试下载 pdf,因此您对问题的处理不正确.不要使用 sendContent().请参阅下文(这是我编写的生产网站的片段,并已证明适用于所有主要浏览器):

Since you are trying to download a pdf, you're approach the problem incorrectly. Do not use sendContent(). See below (this is a snippet from a production site I've written and has proven to work across all major browsers):

$file = '/path/to/file.pdf';
$this->getResponse()->clearHttpHeaders();
$this->getResponse()->setStatusCode(200);
$this->getResponse()->setContentType('application/pdf');
$this->getResponse()->setHttpHeader('Pragma', 'public'); //optional cache header
$this->getResponse()->setHttpHeader('Expires', 0); //optional cache header
$this->getResponse()->setHttpHeader('Content-Disposition', "attachment; filename=myfile.pdf");
$this->getResponse()->setHttpHeader('Content-Transfer-Encoding', 'binary');
$this->getResponse()->setHttpHeader('Content-Length', filesize($file));

return $this->renderText(file_get_contents($file));

这篇关于symfony: setHttpHeader() 不起作用,header() 起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆