2012-06-29 86 views
1

我有以下代碼來推送zip文件進行下載。PHP:強制下載不起作用

$filename = "ResourcePack_".time().".zip"; 
     $destination = $basepath."downloads/$filename"; 
     if($this->createdownload($files,$destination,false)){ 
      header("Cache-Control: public"); 
      header("Content-Description: File Transfer"); 
      header("Content-Length: ". filesize("$destination").";"); 
      header("Content-Disposition: attachment; filename='$filename'"); 
      header("Content-Type: application/octet-stream; "); 
      header("Content-Transfer-Encoding: binary"); 
      ob_end_flush(); 
      @readfile($destination); 

      if(file_exists($destination)){ 
       unlink($destination); 
      } 
     } 

我知道createdownload功能工作,以生成壓縮文件就好了,因爲我看到在服務器上創建的文件。問題是文件正在被寫入瀏覽器作爲一堆垃圾,而不是打開一個下載流。我在頭文件中丟失了什麼嗎?

編輯

我說得對。我的問題不在於php,而是調用通過JQuery $ .ajax調用生成此代碼的php文件是問題。使用$ .ajax會自動將Accept-Encoding請求標頭設置爲與zip文件不兼容的值。因此,使用$ .ajax的intead我只是使用了一個簡單的window.open javascript命令來調用相同的PHP頁面,它的工作原理與標題一致。

+1

嘗試閱讀手冊頭()。有很多人爲強制下載而做出的功能,例如http://us3.php.net/manual/en/function.header.php#102175 –

+1

爲什麼不在啓動之前檢查文件是否存在?因爲如果它不存在,'filesize'將會失敗。 –

+0

我已經讀過它後退和前進。就我所知,我的代碼與其他許多地方相匹配。我在這裏是因爲如果手冊中有些東西可以幫助我解決這個問題,我很想念它。 – LoneWolfPR

回答

0

嘗試爲該文件傳遞正確的類型。我認爲它的FileInfo MIME類型看http://www.php.net/manual/en/ref.fileinfo.php

header("Content-Type: $file_type"); 

而且你有八位字節流後分號刪除

header("Content-type: application/octet-stream"); 
+0

沒有。我想知道這是否與請求頭相關,請求標題說:'Accept-Encoding:gzip,deflate,sdch',但是響應頭類型是'binary',這可能會導致問題嗎? – LoneWolfPR

+0

更新回答關於你有一個分號 – PoX

+0

也許,來自php文檔(標題頁)的文本「另外,請注意,IE版本5,6,7和8已經雙重壓縮-c被壓縮的文件,並且不會正確地反轉進程,所以ZIP文件和類似文件在下載時被損壞。 解決方法:爲這些特定版本的IE禁用壓縮(超出text/html),例如使用Apache的「BrowserMatch」指令。以下示例在所有版本的IE中禁用壓縮功能:「http://www.php.net/manual/es/function.header.php#108766 – jipipayo

0

嘗試將模具@readfile 後,取下@,看看你有任何其他與文件閱讀相關的錯誤。

我有一些代碼做同樣的事情,這對我的作品:

 header("Pragma: public"); 
     header("Expires: 0"); 
     header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
     header("Cache-Control: private", false); // required for certain browsers 
     header('Content-Disposition: inline; filename="' . $filename . '"'); 
     header('Content-type: application/zip'); 
     //header("Content-Transfer-Encoding: binary"); 
     header("Content-Length: " . filesize($destination)); 

     readfile($destination); 
     die(); 
+0

不能。對我無效。來自死亡的錯誤。 – LoneWolfPR