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

使用Laravel和React从服务器下载PDF文件,文件内容为空

解决Axios下载PDF文件为空的问题
  • 核心问题:Axios默认会将响应数据解析为JSON格式,导致二进制PDF数据被错误转换为字符串,生成的Blob自然没有有效内容。
  • 修复步骤:
    1. 在Axios请求配置中添加responseType: 'blob',明确告诉Axios直接返回二进制Blob数据
    2. 无需手动调用JSON.stringify(),直接传入JS对象即可,Axios会自动完成JSON序列化
    3. 若后端对请求头有严格要求,可保留'Content-Type': 'application/json',Axios在传入对象参数时也会自动设置该头

修改后的代码:

await axios.post(URL, { filter }, {
  headers: {
    Authorization: token,
    'Content-Type': 'application/json'
  },
  withCredentials: true,
  responseType: 'blob' // 关键配置,处理二进制响应
}).then((response) => {
  const url = window.URL.createObjectURL(response.data); // 直接使用已处理好的Blob数据
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', 'expense.pdf');
  document.body.appendChild(link);
  link.click();
  // 清理临时URL对象,避免内存泄漏
  window.URL.revokeObjectURL(url);
  document.body.removeChild(link);
});

额外提示:

  • 如果后端返回的是ArrayBuffer类型,可将responseType设为'arraybuffer',再通过new Blob([response.data])转换为Blob使用
  • 务必清理创建的临时URL对象和DOM元素,防止内存占用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:52:02