【问题标题】:symfony: setHttpHeader() doesn't work, header() doessymfony:setHttpHeader() 不起作用,header() 起作用
【发布时间】:2011-03-07 10:43:09
【问题描述】:

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

代码如下:

  $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;

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

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

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 配置问题?我不明白。 :-/

提前致谢!

【问题讨论】:

标签: php symfony1 apache2 http-headers symfony-1.4


【解决方案1】:

你的问题在这里:

return sfView::NONE;

将其更改为:

return sfView::HEADERS_ONLY;

编辑由于额外的 cmets 而更新。

由于您尝试下载 pdf,因此您处理的问题不正确。不要使用sendContent()。见下文(这是我编写的生产站点的 sn-p,已证明可以在所有主要浏览器上工作):

$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));

【讨论】:

  • HEADER_ONLY,不是 HEADERS_ONLY
  • 如果不添加 $this->getResponse()->sendHttpHeaders(); 这对我不起作用
【解决方案2】:

我唯一的区别是:

$response = $this->getContext()->getResponse();
$response->clearHttpHeaders();

【讨论】:

    【解决方案3】:

    遇到同样的问题。只需在文件名周围添加双引号 (")

    $this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename="'.$filename.'"');
    

    header('Content-Disposition: attachment; filename="'.$filename.'"');
    

    【讨论】:

      猜你喜欢
      • 2011-11-03
      • 2012-02-08
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多