2011-05-29 19 views
1

everyone。我與類似的東西堆棧:我必須提供Zend Framework的下載文件功能...幾個小時的谷歌搜索不幫我這個... 所以這裏是我的控制器代碼(注:我是一個初學者):用zend下載文件contextSwitch()動作幫手

//callback 
public function sendFile() 
{ 
    readfile(APPLICATION_PATH . "/../public/pdf/10.pdf"); 
} 

public function init() 
{ 
    $this->_helper->contextSwitch() 
      ->addContext('file', array(
        'headers' => array(
         'Content-Type'   => 'application/pdf', 
         'Content-disposition' => 'attachment; filename="10.pdf"'), 
        'callbacks' => array(
         'init' => '_sendFile' 
       ) 
      )) 
      ->addActionContext('download', 'file') 
      ->setAutoJsonSerialization(false) 
      ->initContext(); 

} 
// ... 
public function downloadAction() 
{ 
} 

PS:我覺得這download files with zend framework,但我想這樣做的Zend方式。 謝謝大家

回答

2

你可以試試。

public function init() 
{ 
    $this->_helper->contextSwitch() 
      ->addContext('file')) 
      ->addActionContext('download', 'file') 
      ->setAutoJsonSerialization(false) 
      ->initContext(); 

} 
// ... 
public function downloadAction() 
{ 
    if ($this->_helper->contextSwitch()->getCurrentContext() == 'file') { 
     $this->getResponse() 
       ->setHeader('Content-type', 'application/pdf; charset=binary') 
       ->setHeader('Content-Disposition', 'attachment; filename="10.pdf"') 
       ->setHeader('Content-length', filesize(APPLICATION_PATH . "/../public/pdf/10.pdf")) 
       ->setHeader('Cache-control', 'private'); 
     readfile(APPLICATION_PATH . "/../public/pdf/10.pdf"); 
     $this->getResponse()->sendResponse(); 
    } else { 
     throw new Zend_Controller_Action_Exception('File not found', 404); 
    } 
} 

還必須設置參數格式文件無論是作爲一個POST或GET變量調用頁面,例如。

<a href="http://yourdomain.com/path/to/controller/format/file"> 

如果您的文件在您的公共文檔文件夾中,您可以直接鏈接到它。

<a href="http://yourdomain.com/pdf/10.pdf"> 

而不用打擾上面的PHP/ZF代碼。

我希望這會有所幫助。

親切的問候

加里

+0

非常感謝你,@Garry!你接近成功的作品!但爲什麼zend開發人員建議通過回調來實現呢? [contextSwitch()回調](http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.contextswitch)非常感謝您的快速回答) – andrew 2011-05-30 13:43:27

+0

還有一件事:if我通過自己的回調($ this-> sendFile()) - 它開始輸出原始的PDF文件正文瀏覽器窗口...爲什麼這樣做。問題在哪裏? – andrew 2011-05-30 13:53:04

+0

[截圖](http://ubuntuone.com/p/wTX/)以前的評論 – andrew 2011-05-30 14:11:02