Laravel中如何处理大文件下载_Laravel实现文件流下载响应【教程】

9次阅读

应使用 response()->stream() 实现大文件流式下载,避免内存溢出;需手动处理 Range 请求支持断点续传,并配置 nginx 等服务器禁用缓冲以确保流响应生效。

Laravel中如何处理大文件下载_Laravel实现文件流下载响应【教程】

response()->stream() 处理大文件,避免内存溢出

直接用 response()->download() 下载几百 MB 以上的文件,php 进程会把整个文件读进内存,极大概率触发 Allowed memory size exhausted。必须改用流式响应,边读边发,内存占用恒定在几 KB。

关键不是“怎么下”,而是“不把文件全 load 进内存”。response()->stream()laravel 提供的底层流接口,它接受一个回调函数,每次由你控制读多少、发多少。

  • 回调函数里用 fopen($path, 'rb') 打开只读流,不要用 file_get_contents()
  • 必须设置正确的 Content-TypeContent-Disposition 响应头,否则浏览器可能无法识别为可下载文件
  • 推荐配合 set_time_limit(0) 防止超时中断(尤其在慢速网络或大文件场景)
public function downloadBigFile($filename) {     $path = storage_path('app/large-files/' . $filename);     if (!file_exists($path)) {         abort(404);     } 
$stream = function () use ($path) {     $handle = fopen($path, 'rb');     while (!feof($handle)) {         echo fread($handle, 8192);         ob_flush();         flush();     }     fclose($handle); };  return response()->stream($stream, 200, [     'Content-Type' => 'application/octet-stream',     'Content-Disposition' => 'attachment; filename="' . basename($path) . '"',     'Content-Length' => filesize($path), ]);

}

为什么不能用 readfile() 直接丢给 response()->download()

response()->download() 内部确实会调用 readfile(),但它会在发送前尝试设置 Content-Length 并做 MIME 类型探测——这个过程本身就会触发完整文件读取或 stat 操作,在某些 NFS 或对象存储挂载路径下反而更慢或失败。

更重要的是:Laravel 的 download() 方法对大文件缺乏流控支持,无法分块 flush,也不允许你干预缓冲行为。一旦 PHP 输出缓冲区(output_buffering)开启,整个文件仍可能被暂存于内存中。

  • 如果服务器启用了 output_buffering = 4096(常见默认值),即使你用 readfile(),数据也会先攒够 4KB 才发,对超大文件无实质改善
  • ob_end_clean()ob_flush()download() 封装内不可控,容易失效
  • 部分 cdn 或反向代理(如 Nginx)会拦截并缓存 Content-Length 已知的响应,导致首次请求延迟高、后续请求返回旧内容

如何支持断点续传(Range 请求)

浏览器或下载工具发起大文件下载时,常带 Range: bytes=1000-2000 头。原生 stream() 不处理这个逻辑,需手动解析并响应 206 Partial Content

核心是读取 Range 头、计算起始/结束偏移、设置 Content-Range 和状态码。注意:必须关闭 Content-Length(改用 Content-Range 中的总长度),且不能使用 ob_flush() 以外的输出控制(否则破坏分块边界)。

  • 务必校验 Range 值是否合法(如负数、超出文件大小)
  • 多个 range(bytes=0-500,1000-1500)极少被客户端用于下载,可忽略,只处理单段
  • Nginx 默认禁用 range 支持,若前端有 Nginx,需确认已开启 range 模块并配置 add_header Accept-Ranges bytes;
public function downloadWithRange($filename) {     $path = storage_path('app/large-files/' . $filename);     $size = filesize($path);     $fp = fopen($path, 'rb'); 
$range = request()->header('Range'); if ($range && preg_match('/^bytes=(d+)-(d+)?/', $range, $matches)) {     $start = (int)$matches[1];     $end = isset($matches[2]) ? (int)$matches[2] : $size - 1;     $length = $end - $start + 1;      fseek($fp, $start);     $headers = [         'Content-Type' => 'application/octet-stream',         'Content-Disposition' => 'attachment; filename="' . basename($path) . '"',         'Content-Range' => "bytes {$start}-{$end}/{$size}",         'Accept-Ranges' => 'bytes',     ];      return response()->stream(function () use ($fp, $length) {         $remaining = $length;         while ($remaining > 0 && !feof($fp)) {             $chunk = min(8192, $remaining);             echo fread($fp, $chunk);             $remaining -= $chunk;             ob_flush();             flush();         }     }, 206, $headers); }  // 普通下载 return response()->stream(function () use ($fp, $size) {     while (!feof($fp)) {         echo fread($fp, 8192);         ob_flush();         flush();     } }, 200, [     'Content-Type' => 'application/octet-stream',     'Content-Disposition' => 'attachment; filename="' . basename($path) . '"',     'Content-Length' => $size,     'Accept-Ranges' => 'bytes', ]);

}

本地开发与生产环境的差异点

本地用 Valet / Homestead 可能一切正常,但上线后下载卡住或 502,往往不是代码问题,而是中间件或 Web 服务器限制。

  • Nginx 默认 fastcgi_buffer_sizefastcgi_buffers 较小,大响应体可能被截断;建议设为 fastcgi_buffer_size 128k; fastcgi_buffers 4 256k; fastcgi_busy_buffers_size 256k;
  • apachemod_deflate 若启用,会对流响应强行压缩,破坏二进制完整性;应在路由中禁用:SetEnv no-gzip 1
  • Laravel 的 TrimStringsConvertEmptyStringsToNull 中间件对流响应无影响,但若你在控制器顶部写了 ini_set('output_buffering', 'on'),会彻底破坏流行为
  • Cloudflare 等 CDN 默认缓存所有 200 响应,且不缓存 206;如需走 CDN,必须显式设置 Cache-Control: private, no-store

实际部署时,最常被忽略的是 Nginx 的 proxy_buffering off(如果你用 Nginx 反代 PHP-FPM)和 fastcgi_max_temp_file_size 0(禁用临时文件缓存)。这两个配置不加,再标准的流代码也白写。

text=ZqhQzanResources