【发布时间】:2020-11-19 00:18:41
【问题描述】:
我正在努力在浏览器中下载 pdf 文件,我已经在后端创建了 pdf,并且可以在后端本地查看该文件,然后我将其保存在 mysql 中(下面的屏幕截图),然后使用 API call我检索到可在浏览器上下载的 pdf 文档,但在尝试下载时显示文件名为 [object object] 和状态 failed:no file。
我环顾四周,看到一些将 pdf 转换为 base64 的地方,但我不确定我是否需要它。请有任何建议。
sn-p of 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")}`);
}
});
- 前端代码的sn-p
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>
【问题讨论】:
标签: javascript mysql node.js reactjs