javascript - 使用 ReactJS MySql 成功生成 PDF 但无法在浏览器中显示为可下载
问题描述
我正在努力在浏览器中下载 pdf 文件,我已经在后端创建了 pdf 并且可以在后端本地查看该文件,然后我将其保存在 mysql 中(下面的屏幕截图),然后使用API call
我检索 pdf 文档到可在浏览器上下载,但failed:no file
在尝试下载时将文件名显示为 [object object] 和状态。我环顾四周,看到一些将 pdf 转换为 base64 的地方,但我不确定是否需要它。请有任何建议。
代码backend-Nodejs
片段_
- 后端- 通过 API 调用发送文件
let token = req.cookies.access_token;
if (token) {
let Invoice_No_Actual = req.body.invoice_Name;
// the below two res.set has been set now
res.set("Content-disposition", "attachment; filename=" + `${__dirname}\\` + `${Invoice_No_Actual}` + `.pdf`);
res.contentType("application/pdf");
res.send(`data:application/pdf;base64,${new Buffer.from(data).toString("base64")}`);
}
});
- 前端代码片段
console.log("content", content);// this content if i convert online tool it does shows the correct PDF file
const blob = new Blob([content], { type: "application/pdf" });
console.log(blob);
const link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
};
const generatePdf = (invoice_Name) => {
let invoice_Object = {
invoice_Name: invoice_Name,
};
const headers = new Headers();
headers.append("content-type", "application/json");
headers.append("responseType", "blob");
// headers.append("responseType", "blob");
const options = {
method: "POST",
headers,
credentials: "include",
body: JSON.stringify(invoice_Object),
};
const newRequest = new Request("http://localhost:5000/api/invoice-only", options);
(async () => {
const invoice_Call = await fetch(newRequest)
.then((res) => {
return res.text();
})
.then((data) => {
generateFile(data, invoice_Name);
});
})();
};
- 触发的前端代码
API call
let invoice_Name = `${users_user_id}` + `_` + `${invoiceNo}`;
// to get the specific invoice (userid_invoiceNO) usefull to get specific file from backend
<span role="button" tabIndex="-1" onKeyDown={() => generatePdf(invoice_Name)} onClick={() => generatePdf(invoice_Name)}>invoiceNo:{invoiceNo}
</span>
解决方案
If you are sending the above file through your API as an attachment then you want to use a javascript blob to read the file since it's non-native.
const generateFile = (content, fileName) => {
const blob = new Blob([content]);
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
const generatePdf = () => {
(...some api request here)
.then(res => {
...catching the response here
const filename = 'new_file.pdf'; // You can get this name from the API
generateFile(res, filename))
.catch(.....)
}
return (
<span
role="button"
tabIndex="-1"
onKeyDown={generatePdf}
onClick={generatePdf}
>
Download PDF
</span>
)
Here we are creating a new Blob from the content sent through the API and then triggering a download popup to show up in the browser.
推荐阅读
- python - 熊猫将一个df中的日期与另一个df中的时间框架匹配,然后是groupby-sum
- angular - 错误类型错误:无法读取未定义 Angular 6 的属性“mData”
- java - 使用嵌套 for 循环添加 2 个带有 java.util.ListIterator 的链接列表;
- amazon-web-services - 通过 Terraform 或 Cloudformation 启用和配置 AWS Cognito 高级安全功能
- ruby-on-rails - Ruby on Rails - 单选内联按钮 - 为什么此选项显示为真/假?
- angular - 我如何将从 post 请求中收到的数据分配给 observable?- 离子3
- javascript - redux-saga 两次调用 - reactjs
- ios - 如何将数据传递给模型类并从模型类中获取数据 - swift
- javascript - Ember addPackageToProject 或 addBowerPackageToProject
- algorithm - 找出到达迷宫任何角落的最小步骤?