Laravel API对接React前端下载PDF文件返回空文件问题求助
问题原因
你的HTTP客户端默认将PDF二进制响应解析为UTF-8文本,导致二进制内容被不可逆转码损坏,因此即使内容看起来是完整的PDF结构,生成的Blob也不是可用的原始文件。
修复方案
1. 服务端可选优化
你可以先确认Laravel端返回正确的响应头,避免客户端识别异常:
public function servePDF($statement_id) { $statement = Statement::where('id', $statement_id)->first(); if($statement === null){ return response()->json(['message' => "Statement does not exist.", "success" => false], 404); } $full_path = $this->pdf_path.$statement->filename; $storage_path = storage_path('app/generated/'.$full_path); return response()->file($storage_path, [ 'Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="'.$statement->filename.'"' ]); }
2. 客户端核心修改
请求时强制指定响应类型为blob,不要让客户端默认解析为文本:
如果你的httpClient是Axios类的封装,修改请求参数:
download: (resource, params) => { return httpClient(`${apiUrl}/${resource}/download/${params.id}`, { method: 'GET', // 关键配置:指定响应为二进制blob类型 responseType: 'blob' }).then((res) => { return { 'data': res.body } }); }
如果你的httpClient是基于原生Fetch封装,修改解析逻辑:
download: (resource, params) => { return fetch(`${apiUrl}/${resource}/download/${params.id}`, { method: 'GET' }).then(async (res) => { return { // 直接用blob方法解析二进制响应 'data': await res.blob() } }); }
原有下载触发逻辑无需修改,即可正常生成可用的PDF文件。
内容的提问来源于stack exchange,提问作者peterxz
相关产品推荐
相关产品推荐

