PHPLaravel开发实践PHP经验分享

PHP下载文件、限速、X-sendfile

2017-12-05  本文已影响94人  小小聪耶

一、普通文件下载

①laravel框架HTTP响应的download方法

$pathToFile = 'myfile.csv';//参数一:绝对路径
$downloadName = 'downloadFile.csv';//参数二:下载后的文件名
//download 参数三:HTTP头信息
return response()->download($pathToFile, $downloadName);

②PHP实现

 $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的问题。

但是这种方法将文件内容从磁盘经过一个固定的 buffer 去循环读取到内存,再发送给前端 web 服务器,最后才到达用户。当需要下载的文件很大的时候,这种方式将消耗大量内存,甚至引发 php 进程超时或崩溃,接下来就使用到X-Sendfile。

三、X-Sendfile

我是用的nginx,所以apache请参考https://tn123.org/mod_xsendfile/
①首先在配置文件中添加

location /download/ {
  internal;
  root   /some/path;//绝对路径
}

②重启Nginx,写代码

$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 . '不存在');
}

image.png

如果你还想了解更多关于X-sendfile,请自行查阅

上一篇 下一篇

猜你喜欢

热点阅读