2012-06-26 38 views
2

我想實現的目標: 強制下載一個包含用戶選擇的pdf文件的zip文件。用winrar打開時,通過Cakephp MediaViews報告獲取Zip文件意外的存檔結束

我在做什麼控制器來實現這一點:

  1. 生成文件夾APP.WEBROOT_DIR.DS PDF報告 「package_files」(我用MPDF庫) *它產生正確讀取PDF。我在這裏調用$ this-> render();

  2. 用PHP的拉鍊功能,生成package.zip(從指定的文件夾上面包括PDF文件) *它生成正確的zip文件,從服務器下載時,它會打開Windows作爲有效的壓縮文件。

  3. 將控制器viewClass設置爲媒體並將參數設置爲強制下載爲zip文件, *在這裏我再次調用$ this-> render(); 期: 當我運行我得到的zip文件,但與winrar打開時,Zip文件獲取報告意外的存檔結束。

我沒有得到任何有用的物品通過這個問題來獲得...

什麼,我想呼籲兩次渲染正在文件損壞 感謝

我的控制器代碼:

/** before this code i generate pdf files and have no issue **/

/** now scan through the directory and add all the pdf files to a zip archive **/

$dir = new Folder("".APP.WEBROOT_DIR.DS."package_files"); 


    $files = $dir->find('.*\.pdf'); 
    $zip = new ZipArchive(); 
    foreach ($files as $file) { 
     $file_path = $dir->pwd() . DS . $file; 


     $filename = $dir->pwd() . DS ."package.zip"; 

     if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) { 
      exit("cannot open <$filename>\n"); 
     } 
     $zip->addFile($file_path,$file); 




    } 

    $zip->close(); 

/** now render the action to download the generated zip file **/

 $this->viewClass = 'Media'; 


     $params = array(
      'id'  => 'package.zip', 
      'name'  => 'packaged_file', 
      'download' => true, 
      'extension' => 'zip', 
      'path'  => APP . WEBROOT_DIR.DS.'package_files' . DS 
     ); 
     $this->set($params); 
    $this->render(); 

回答

0
在最前一頁

,如果你使用CakePHP 2.3ü SE蛋糕響應文件instaed mediaView與這些結構:

$this->response->file($file['path']); 
// Return response object to prevent controller from trying to render 
// a view 
return $this->response; 

這裏DOC:http://book.cakephp.org/2.0/en/controllers/request-response.html#cake-response-file

否則刪除$這個 - >渲染();在動作結束時指定MIME類型選項,專門用於zip和rar文件,例如用於docx文件添加MIME類型選項,如:

// Render app/webroot/files/example.docx 
    $params = array(
     'id'  => 'example.docx', 
     'name'  => 'example', 
     'extension' => 'docx', 
     'mimeType' => array(
      'docx' => 'application/vnd.openxmlformats-officedocument' . 
       '.wordprocessingml.document' 
     ), 
     'path'  => 'files' . DS 
    ); 
相關問題