symfony: setHttpHeader() doesn't work, header(

2019-04-07 21:47发布

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

Here's the code:

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

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

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. :-/

Thanks in advance!

3条回答
太酷不给撩
2楼-- · 2019-04-07 22:20

The only difference that I have is:

$response = $this->getContext()->getResponse();
$response->clearHttpHeaders();
查看更多
欢心
3楼-- · 2019-04-07 22:22

Your problem is here:

return sfView::NONE;

Change this to:

return sfView::HEADERS_ONLY;

edit update due to extra comments.

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));
查看更多
放我归山
4楼-- · 2019-04-07 22:24

Got the same problem. Just add double quotes (") around the filename

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

or

header('Content-Disposition: attachment; filename="'.$filename.'"');
查看更多
登录 后发表回答