VueJS下载PDF为空提示无法加载PDF文档问题排查求助
问题根因
Postman可正常获取PDF说明后端接口逻辑无问题,故障出在前端对二进制响应的处理环节,核心有三个常见错误:
- 发送请求时未指定
responseType: 'blob',导致请求库默认将PDF二进制流按字符串解析,出现编码损坏 - 未正确取到响应体中的二进制内容(若使用Axios等请求库,响应内容默认包裹在
response.data字段中,直接传整个response对象会导致内容为空) - 下载逻辑错误,直接将二进制内容拼接为data URL的方式不适用PDF等二进制文件
修复步骤
1. 调整请求配置
在你的fetchContractAgreement请求逻辑中新增responseType: 'blob'配置,以Axios为例:
// 示例:fetchContractAgreement方法调整 async function fetchContractAgreement(params) { return axios.get(`/api/${params.id}/contract-agreement`, { params: params.filters, responseType: 'blob' // 必须添加,告诉请求库返回二进制Blob对象 }) }
2. 修正响应内容取值
如果使用Axios等封装过的请求库,需要取response.data作为文件内容传入下载方法:
await this.fetchContractAgreement({ id: document, filters: this.filters }).then(response => { // 取response.data而非整个response对象 this.downloadFile2(response.data, fileName) })
3. 重写下载逻辑
改用Blob+Object URL的方式生成下载地址,同时处理内存释放:
downloadFile2 (blobContent, fileName) { const blob = new Blob([blobContent], { type: 'application/pdf' }) const fileURL = window.URL.createObjectURL(blob) const fileLink = document.createElement('a') fileLink.href = fileURL fileLink.setAttribute('download', fileName) document.body.appendChild(fileLink) fileLink.click() // 清理临时对象避免内存泄漏 document.body.removeChild(fileLink) window.URL.revokeObjectURL(fileURL) }
验证方法
调整后打印传入downloadFile2的参数,确认是Blob类型对象即可正常生成PDF文件。
内容的提问来源于stack exchange,提问作者grozdeto
相关产品推荐
相关产品推荐

