[英]PDF generated successfully but not showing as downloadable in the browser using ReactJS MySql
我正在努力在瀏覽器中下載 pdf 文件,我在后端創建了 pdf,可以在后端本地看到該文件,然后我將它保存在 mysql(下面的屏幕截圖)中,然后使用API call
我檢索 pdf文檔可在瀏覽器上下載,但它顯示文件名為 [object object] 並且狀態failed:no file
。 我環顧四周,看到一些地方可以將 pdf 轉換為 base64,但我不確定是否需要它。 請有任何建議。
backend-Nodejs
代碼片段
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>
如果您將上述文件作為附件通過 API 發送,那么您需要使用javascript blob來讀取該文件,因為它不是本地文件。
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>
)
在這里,我們根據通過 API 發送的內容創建一個新的 Blob,然后觸發下載彈出窗口顯示在瀏覽器中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.