javascript - js api返回的PDF为空
问题描述
我正在使用车把和 puppeteer 在我的 express api/server 端生成 PDF 报告。使用 insomnia 触发 API,它返回一个完整的 PDF,完全符合我的预期。当我让客户端 React 应用程序下载它时,它会保存正确数量的页面,但为空。我尝试了多种下载文件的方法,API 端的标头。这是当前代码。
前端:
const res = await getDashboard(company, category, country, endDate, startDate);
const blob = new Blob([res], { type: 'application/pdf' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'amazon.pdf';
a.click();
服务器端:
const pdf = await genReport(data);
res.contentType('application/pdf');
res.header('Pragma', 'public');
res.header('Cache-Control', 'max-age=0');
res.setHeader('Content-disposition', 'attachment;filename=AmazonReport.pdf');
res.type('application/pdf');
res.send(pdf);
我不确定我哪里出错了。由于 insomnia 收到 PDF 罚款,我假设它的客户端处理。请帮忙。
解决方案
@georgedum 在这里为我指明了正确的方向,问题现已解决。这是更新/修复的代码:客户端:
const res = await getDashboard(company, category, country, endDate, startDate);
const binaryString = window.atob(res);
const binaryLen = binaryString.length;
const bytes = new Uint8Array(binaryLen);
for (let i = 0; i < binaryLen; i++)
{
const ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
const blob = new Blob([bytes], { type: 'application/pdf' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'amazon.pdf';
a.click();
服务器端:
const pdf = await genReport(data);
const encodedPdf = Buffer.from(pdf).toString('base64');
res.contentType('application/pdf');
res.header('Pragma', 'public');
res.header('Cache-Control', 'max-age=0');
res.setHeader('Content-disposition', 'attachment;filename=AmazonReport.pdf');
res.type('application/pdf');
res.send(encodedPdf);
推荐阅读
- android - Espresso IntentsTestRule 上的多项活动测试
- git - Git:提交冲突和提交回滚
- postgresql - 如何使用另一个表中的 where 子句进行选择计数(*)返回空行?
- python - Selenium python错误:元素无法滚动到视图中
- java - ClassNotFoundException 只有类?
- android - 使用字符串资源创建超链接
- r - 用字符串减去列
- ios - Swift - 打字时TextView高度和宽度发生变化
- ios - 视图转到表格视图,表格不起作用
- c++ - 在 C++ 中使用 Qt 在 Linux 上连接到 Oracle DB