我用javascript和php编写了一个下载脚本。它的工作,但如果我想下载一个大文件(例如1GB的zip文件),它有太长时间结束与请求。我想这和我读了文件有关。如果是这样,有什么办法更快吗?
注意:我需要一个标题,因为强制下载像图像,pdf,任何类型的文件类型。
JS非常简单。看这个:
function downloadFile(file){
document.location.href = "script.php?a=downloadFile&b=."+ file;
}
PHP还很简单:
function downloadFile($sFile){
#Main function
header('Content-Type: '.mime_content_type($sFile));
header('Content-Description: File Transfer');
header('Content-Length: ' . filesize($sFile));
header('Content-Disposition: attachment; filename="' . basename($sFile) . '"');
readfile($sFile);
}
switch($_GET['a']){
case 'downloadFile':
echo downloadFile($_GET['b']);
break;
}
我想缓冲是大文件的问题。尝试以小块(如兆字节)读取文件,并在打印每个块后调用flush函数来刷新输出缓冲区。
编辑:嗯,好吧,这是你应该尝试的代码示例:
function downloadFile($sFile){
#Main function
if ( $handle = fopen( $sFile, "rb" ) ) {
header('Content-Type: '.mime_content_type($sFile));
header('Content-Description: File Transfer');
header('Content-Length: ' . filesize($sFile));
header('Content-Disposition: attachment; filename="' . basename($sFile) . '"');
while ( !feof($handle) ) {
print fread($handle, 1048576);
flush();
}
fclose($handle);
} else {
header('Status: 404');
header('Content-Type: text/plain');
print "Can't find the requested file";
}
}