Laravel下载用response download吗

wen PHP项目 2

本文目录导读:

Laravel下载用response download吗

  1. 基本用法
  2. 从存储系统下载
  3. 从 public 目录下载
  4. 实际控制器示例
  5. 其他相关方法
  6. 注意事项

是的,Laravel 中下载文件主要使用 response()->download() 方法。

基本用法

// 最简单的用法
return response()->download($pathToFile);
// 自定义文件名
return response()->download($pathToFile, 'custom_name.pdf');
// 带数组头信息
return response()->download($pathToFile, 'file.pdf', [
    'Content-Type' => 'application/pdf',
]);

从存储系统下载

// 从 storage/app 目录下载
$file = storage_path('app/reports/report.pdf');
return response()->download($file);
// 使用 Storage facade
use Illuminate\Support\Facades\Storage;
public function download()
{
    return Storage::disk('public')->download('files/document.pdf', 'document.pdf');
}

从 public 目录下载

// public 目录下的文件
$publicPath = public_path('uploads/file.jpg');
return response()->download($publicPath);

实际控制器示例

class FileController extends Controller
{
    public function download($id)
    {
        $file = File::findOrFail($id);
        // 检查文件是否存在
        if (!Storage::disk('public')->exists($file->path)) {
            abort(404, '文件不存在');
        }
        return response()->download(
            storage_path('app/public/' . $file->path),
            $file->original_name,
            ['Content-Type' => $file->mime_type]
        );
    }
}

其他相关方法

response()->file() - 在浏览器中显示文件

// 直接在浏览器显示图片或 PDF,而不是下载
return response()->file($pathToFile);

StreamedResponse - 大文件下载

use Symfony\Component\HttpFoundation\StreamedResponse;
public function streamDownload()
{
    return new StreamedResponse(function () {
        $outputStream = fopen('php://output', 'w');
        // 从数据库或外部源流式输出
    }, 200, [
        'Content-Type' => 'application/octet-stream',
        'Content-Disposition' => 'attachment; filename="largefile.csv"',
    ]);
}

注意事项

  1. 文件路径:使用 absolute path(绝对路径)
  2. 文件权限:确保 Web 服务器有读取权限
  3. 大文件:建议使用流式传输(StreamedResponse)
  4. 中文文件名:可能出现乱码,建议使用 URL 编码
// 处理中文文件名
$fileName = rawurlencode('中文文件.pdf');
return response()->download($filePath, $fileName);

response()->download() 是 Laravel 中最常用、最便捷的文件下载方式,满足大多数场景需求。

抱歉,评论功能暂时关闭!