下载脚本极其缓慢
我已经用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";
}
}
我真的很想使用浏览器下载。如果我打开www.example.com/some.zip,浏览器会自动启动以下载文件。是否没有机会使用任何扩展名文件(图片,PDF文件,..?)来下载这个强制文件?还是我必须用块文件发回一个文件头? – Sylnois 2013-03-04 15:22:19
呃,什么?我已经用一个你应该尝试的例子更新了答案。 – JackTheRandom 2013-03-04 16:44:03
你可以从你的交换机到downloadFile中的回声,而不是读取一气呵成整个文件,块,这也使一次读取和回放一小部分文件。 – NickSlash 2013-03-04 14:35:37