Express JS如何向客户端发送Blob?解决PDF下载空白问题
问题:Express后端返回Blob文件后,前端PDF显示空白且标题乱码
我正尝试从Web应用下载文件:点击下载按钮后前端向后端发起POST请求,后端会编辑Google Drive中的文件并导出为Blob,再返回给前端,但生成的PDF打开后显示空白,标题为乱码。
Google Drive API导出的Blob格式示例
{ id: '10i7fTyLEmhovfArrbI_1Kvk-pwWRpwU-QgCWnINSQqQ', file: Blob { [Symbol(type)]: 'application/pdf', [Symbol(buffer)]: <Buffer 5 25 50 44 46 2d 31 2e 34 0a 25 20 e2 e3 cf d3 ... 3663411 more bytes> } }
后端(Express)代码
router.post("/getFiles", async (req, res) => { const blob = await /* 从Google Drive获取的文件Blob */; res.header("Content-Type", "application/pdf"); res.header("Content-Length", blob.size); blob.stream().pipe(res); });
原前端(Axios)代码
axios.post(address, payload) .then(response => { const blob = new Blob([response?.data], { type: "application/pdf" }) resolve(window.URL.createObjectURL(blob)); }) .catch(err => reject(err));
解决方案
问题出在Axios的默认响应解析行为:Axios默认会将响应数据解析为JSON,导致二进制的Blob数据被损坏。只需在POST请求配置中添加{ responseType: "blob" },明确告诉Axios以Blob格式接收响应:
axios.post(address, payload, { responseType: "blob" }) .then(response => { const blob = new Blob([response?.data], { type: "application/pdf" }) resolve(window.URL.createObjectURL(blob)); }) .catch(err => reject(err));
内容的提问来源于stack exchange,提问作者ldekester
相关产品推荐
相关产品推荐

