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,存在两个关键错误:
- 路径参数错误:
Storage::download()的第一个参数是相对于磁盘根目录的路径,public盘的根目录对应storage/app/public,因此无需添加public/前缀,正确路径为files/'.$filename - 前端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
相关产品推荐
相关产品推荐

