①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
記得關注我呦後端