NodeJS后端对接React前端下载文件出现PDF损坏问题如何解决?
问题核心原因
前端axios请求配置中responseType: "blob"放置位置错误,该参数是axios的顶层请求配置项,不属于headers字段,配置不生效导致axios默认将返回的PDF二进制数据按文本格式解析,造成文件损坏。
修复方案
1. 修正前端axios请求配置
将responseType从headers中移出,放到请求配置的顶层,同时补充优化逻辑:
const downloadTraining = async (id) => { const JWT = new ClassJWT(); const axiosReq = axios.create(); await JWT.checkJWT(); axiosReq .get(`${serverPath}/download-training`, { headers: { training_id: id, token: JWT.getToken() }, // responseType为顶层配置,移到此处 responseType: "blob" }) .then((response) => { // 显式指定blob的MIME类型,避免兼容性问题 const url = window.URL.createObjectURL(new Blob([response.data], {type: 'application/pdf'})); const link = document.createElement("a"); link.href = url; link.setAttribute("download", "file.pdf"); document.body.appendChild(link); link.click(); // 下载完成后释放内存,避免内存泄漏 window.URL.revokeObjectURL(url); document.body.removeChild(link); }) .catch((err) => console.log(err)); };
2. 后端可选优化(避免响应头异常)
手动指定PDF对应的响应头,确保返回格式符合预期:
routerTrainer.get("/download-training", verifyJWT, async (req, res) => { const { training_id } = req.headers; let training = await Training.findOne({ where: { id: training_id }, }); if (training) { const filePath = `${path}${dirname}${training.file_id}`; // 手动指定响应头 res.setHeader('Content-Type', 'application/pdf'); res.setHeader('Content-Disposition', `attachment; filename=file.pdf`); res.download(filePath); } else { res.status(404).send('未找到对应培训文件'); } });
3. 其他排查点
- 检查后端文件路径拼接是否正确,可打印
filePath确认能正常访问到源PDF文件 - 确认源PDF文件本身没有损坏,可直接在服务器上打开验证
内容的提问来源于stack exchange,提问作者Gonsa02
相关产品推荐
相关产品推荐

