You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel通过Axios下载PDF遇500错误及空白文件问题求助

Laravel 存储PDF下载500错误及空白PDF问题解决

一、原代码500错误的原因及修复

原show方法的核心问题是混淆了Storage::get()的返回值与文件路径的用法:

  • Storage::disk('public')->get("files/".$filename)返回的是文件的二进制内容,而非文件系统的物理路径
  • 将内容传给file_get_contents()必然报错,因为该函数要求传入文件路径,而非文件内容

修复后的代码(不使用download方法的方案):

public function show(string $filename)
{
    $filePath = "files/".$filename;
    if(Storage::disk('public')->exists($filePath))
    {
        $content = Storage::disk('public')->get($filePath);
        // 通过Storage的path方法获取真实物理路径,用于获取MIME类型
        $realPath = Storage::disk('public')->path($filePath);
        return response($content)->withHeaders([
            'Content-Type' => mime_content_type($realPath),
            'Content-Disposition' => 'attachment; filename="' . $filename . '"'
        ]);
    }
    abort(404);
}

二、修改后PDF空白的问题修复

使用Storage::download()后出现空白PDF,存在两个关键错误:

  1. 路径参数错误:Storage::download()的第一个参数是相对于磁盘根目录的路径,public盘的根目录对应storage/app/public,因此无需添加public/前缀,正确路径为files/'.$filename
  2. 前端Axios配置错误:responseType: 'blob'属于请求配置项,需放在配置的顶层,而非headers对象内

后端正确代码

public function show(string $filename)
{
    $filePath = "files/".$filename;
    if (Storage::disk('public')->exists($filePath)) {
        return Storage::disk('public')->download($filePath, $filename, [
            'Content-Type' => 'application/pdf',
        ]);
    }
    abort(404);
}

前端Axios正确配置

const getFile = (filename) => {
    axios.get(
        "http://localhost:8000/api/files/" + filename,
        {
            headers: {
                Authorization: "Bearer " + localStorage.getItem("token"),
                Accept: "application/pdf"
            },
            responseType: "blob" // 移至配置顶层,而非headers中
        }
    )
    .then((res) => {
        const file = new Blob([res.data], { type: "application/pdf" });
        const fileURL = URL.createObjectURL(file);
        // 用a标签实现稳定下载,替代window.open
        const a = document.createElement('a');
        a.href = fileURL;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(fileURL); // 释放浏览器资源
    })
    .catch((err) => {
        console.log(err);
    });
};

补充检查项

  • 确保storage/app/public/files目录存在且具备读写权限
  • 已执行php artisan storage:link命令(API下载场景非强制,但可确保存储路径映射正确)

内容的提问来源于stack exchange,提问作者MISIU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 22:07:39