①laravel框架HTTP响应的download方法php
$pathToFile = 'myfile.csv';//参数一:绝对路径 $downloadName = 'downloadFile.csv';//参数二:下载后的文件名 //download 参数三:HTTP头信息 return response()->download($pathToFile, $downloadName);
②PHP实现html
$pathToFile = 'myfile.csv';//文件绝对路径 $downloadName = 'downloadFile.csv';//下载后的文件名 //输入文件标签 Header("Content-type: application/octet-stream"); Header("Accept-Ranges: bytes"); Header("Accept-Length: " . filesize($pathToFile)); Header("Content-Disposition: filename=" . $downloadName); //输出文件内容 $file = fopen($pathToFile, "r"); echo fread($file, filesize($pathToFile)); fclose($file); //或 //readfile($pathToFile);
其中fread()与readfile()的区别能够参考https://segmentfault.com/q/10...
可是有时候为了节省带宽,避免瞬时流量过大而形成网络堵塞,就要考虑下载限速的问题前端
$pathToFile = 'myfile.csv';//文件绝对路径 $downloadName = 'downloadFile.csv';//下载后的文件名 $download_rate = 30;// 设置下载速率(30 kb/s) if (file_exists($pathToFile) && is_file($pathToFile)) { header('Cache-control: private');// 发送 headers header('Content-Type: application/octet-stream'); header('Content-Length: ' . filesize($pathToFile)); header('Content-Disposition: filename=' . $downloadName); flush();// 刷新内容 $file = fopen($pathToFile, "r"); while (!feof($file)) { print fread($file, round($download_rate * 1024));// 发送当前部分文件给浏览者 flush();// flush 内容输出到浏览器端 sleep(1);// 终端1秒后继续 } fclose($file);// 关闭文件流 } else { abort(500, '文件' . $pathToFile . '不存在'); }
此时出现一个问题,当$download_rate>1kb时,文件正常下载;当$download_rate<1kb时,文件要等一下子才下载,究其缘由是由于buffer的问题。nginx
可是这种方法将文件内容从磁盘通过一个固定的 buffer 去循环读取到内存,再发送给前端 web 服务器,最后才到达用户。当须要下载的文件很大的时候,这种方式将消耗大量内存,甚至引起 php 进程超时或崩溃,接下来就使用到X-Sendfile。laravel
我是用的nginx,因此apache请参考https://tn123.org/mod_xsendfile/
①首先在配置文件中添加web
location /download/ { internal; root /some/path;//绝对路径 }
②重启Nginx,写代码apache
$pathToFile = 'myfile.csv';//文件绝对路径 $downloadName = 'downloadFile.csv';//下载后的文件名 $download_rate = 30;// 设置下载速率(30 kb/s) if (file_exists($pathToFile) && is_file($pathToFile)) { return (new Response())->withHeaders([ 'Content-Type' => 'application/octet-stream', 'Content-Disposition' => 'attachment;filename=' . $downloadName, 'X-Accel-Redirect' => $pathToFile,//让Xsendfile发送文件 'X-Sendfile' => $pathToFile, 'X-Accel-Limit-Rate' => $download_rate, ]); }else { abort(500, '文件' . $pathToFile . '不存在'); }
若是你还想了解更多关于X-sendfile,请自行查阅segmentfault
记得关注我呦后端