我試圖獲得一個鏈接,可以在不重定向的情況下下載文件,也可以使用其他文件下載大型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();
}
}
檢查你的最大上傳大小限制在你的'php.ini'文件中。 – 2014-10-01 21:19:49
不確定是否有問題,請查看我的更新。 – David 2014-10-02 04:26:14