2014-10-01 92 views
2

我試圖獲得一個鏈接,可以在不重定向的情況下下載文件,也可以使用其他文件下載大型zip文件。php下載大文件失敗

它適用於大約100MB以下的文件,但任何文件都會更大,並且會發送到鉻合金中的錯誤頁面:Error code: ERR_INVALID_RESPONSE

將$ file和$ path放入帶有jQuery的窗體中,然後調用$('form').submit();

function downloadFile($file, $path){ 

     set_time_limit(0); 
     $fullPath = $path . $file; 

     if ($fd = fopen ($fullPath, "r")) { 


      $fsize = filesize($fullPath); 
      $path_parts = pathinfo($fullPath); 



      $ext = strtolower($path_parts["extension"]); 
      switch ($ext) { 
       case "pdf": 
       header("Content-type: application/pdf"); // add here more headers for diff. extensions 
       header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download 
       break; 
       default; 
       header("Content-type: application/octet-stream"); 
       header("Content-Disposition: filename=\"".$path_parts["basename"]."\""); 
      } 
      header("Content-length: $fsize"); 
      header("Cache-control: private"); //use this to open files directly 
      while(!feof($fd)) { 
       $buffer = fread($fd, 2048); 
       echo $buffer; 
      } 
     } 
     fclose ($fd); 
     exit; 
    } 

任何想法爲什麼它在較大的文件上失敗?

更新: 當我使用下面的代碼,它下載的文件,但因爲它的損壞出於某種原因已完成的文件打不開:

set_time_limit(0); 
ini_set('memory_limit', '1024M'); 
// http headers for downloads 
header("Pragma: public"); 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Cache-Control: public"); 
header("Content-Description: File Transfer"); 
header("Content-type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=\"".$filename."\""); 
header("Content-Transfer-Encoding: binary"); 
header("Content-Length: ".$file_size); 
ob_end_flush(); 
@readfile($fileinfo['path']); 

當我使用此代碼,它僅下載然後第一49.7kb說,它的完成,我甚至試過ob_flush()flush()在一起:

// http headers for downloads 
    header("Pragma: public"); 
    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Cache-Control: public"); 
    header("Content-Description: File Transfer"); 
    header("Content-type: application/octet-stream"); 
    header("Content-Disposition: attachment; filename=\"".$filename."\""); 
    header("Content-Transfer-Encoding: binary"); 
    header("Content-Length: ".filesize($fileinfo['path'])); 

    if ($fd = fopen ($fileinfo['path'], "r")) { 

      set_time_limit(0); 
      ini_set('memory_limit', '1024M'); 

     while(!feof($fd)) { 
      echo fread($fd, 4096); 
      flush(); 
     } 

    } 
+1

檢查你的最大上傳大小限制在你的'php.ini'文件中。 – 2014-10-01 21:19:49

+0

不確定是否有問題,請查看我的更新。 – David 2014-10-02 04:26:14

回答

4

我做的唯一不同,我下載是Content-Transfer-Encoding: chunked。也請將flush()從循環中取出,並確保您在發送數據之前執行ob_clean(); flush();ob_end_flush();

+0

ob_clean();沖洗();在此之前或之前? – David 2014-10-03 02:49:13

+0

在'while'之前... – MBaas 2014-10-03 12:44:04

+0

Ok很好。減去它在控制檯打開時將亂碼扔進控制檯的事實。回聲fread($ fd,4096)導致這個,但刪除它停止工作 – David 2014-10-06 03:05:33