2014-10-01 125 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