[英]PHP download file: show progress in browser
我网站上的用户可以下载文件。 有时这些文件很大,我希望用户在其浏览器上看到下载进度栏。
我使用以下代码为用户提供文件:
header('Content-Type: text/xml');
header('Content-Disposition: attachment; filename='.$fileName);
header('Pragma: no-cache');
header('Content-Transfer-Encoding: binary');
header('Pragma: public');
header('Content-Length: '.filesize($fullFileName));
header("Content-Description: File Transfer");
$fileHandler = fopen($fullFileName, 'r');
while(!feof($fileHandler)){
echo fread($fileHandler, 2048);
}
fclose($fileHandler);
当我运行此脚本浏览器(FireFox)冻结了一段时间后,才可以看到正在加载色环,并且仅在出现保存/打开对话框文件之后。 当我单击“保存”按钮时,文件几乎立即下载到我的计算机上(而文件很大-50 Mb)。
我想在这个站点上有像这样的下载系统。 单击任何链接后,将立即出现“保存/显示”对话框。 之后,您可以在浏览器中看到下载进度。
浏览器中是否有任何特殊的标题显示进度条? 我应该如何更改代码?
我使用下面的代码,在Firefox中,它确实为我提供了下载时间和进度:
// send headers first
header('Content-type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-disposition: attachment; filename='.$FileName);
header("Content-Length: ".filesize($Path));
// then use an easy way to flush and end all output buffers
while (@ob_end_flush());
// flush file
readfile($Path);
如果您正确指定了Content-Length
它应该可以工作。 我在代码中发现的唯一奇怪的地方是Content-Type: text/xml
标头。 请注意,我使用Content-type: application/octet-stream
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.