考虑到服务器性能优化,有时需要限制用户的下载速度。
$filepath = 'public/files/202204231879.xlsx';
$download_rate = 500; // 设置下载速率(500 kb/s)
if (file_exists($filepath) && is_file($filepath)) {
header('Cache-control: private'); // 发送 headers
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize($filepath));
header('Content-Disposition: filename=202204231879.xls');
flush(); // 刷新内容
$file = fopen($filepath, "r");
while (!feof($file)) {
echo fread($file, round($download_rate * 1024)); // 发送当前部分文件给浏览者
flush(); // flush 内容输出到浏览器端
sleep(1); // 终端1秒后继续
}
fclose($file); // 关闭文件流
} else {
die('文件' . $filepath . '不存在');
}
实测有效