2011-03-07 60 views
6

我在symfony中構建了一個簡單的動作,它通過wkhtmltopdf生成一個PDF文件並將其輸出到瀏覽器。symfony:setHttpHeader()不起作用,header()做

下面的代碼:

$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()函數在我的行動手動設置,螢火顯示標題爲預期。 有人知道什麼可能是錯的?它是一個symfony錯誤,或者一個php或apache2配置問題?我不明白。 : -/

在此先感謝!

+0

@teonanacatl ...選擇你的一個帳戶並使用它當前正在使用清楚兩個不同的帳戶的http:。/ /stackoverflow.com/users/647993/teonanacatl和http://stackoverflow.com/users/480353/teonanacatl –

回答

10

你的問題是在這裏:

return sfView::NONE; 

更改爲:

return sfView::HEADERS_ONLY; 

編輯更新,由於要額外評論。

由於您正在嘗試下載pdf,因此您錯誤地處理了該問題。請勿使用sendContent()。見下面(這是從生產現場我已經寫了,並證明所有主流瀏覽器的工作片段):

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

HEADER_ONLY,而不是HEADERS_ONLY –

+0

如果不添加$ this-> getResponse() - > sendHttpHeaders ); – Jestep

0

,我有唯一的區別是:

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

得到了同樣的問題。只需添加雙引號(「)將文件名

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

header('Content-Disposition: attachment; filename="'.$filename.'"'); 
相關問題