![](/img/trans.png)
[英]Getting the image file from the server and converting it to base64 using nodejs express.js
[英]Express.js - how to download base64 string as PDF file?
我有 pdf 文件編碼為 base64 字符串。 如何將此字符串作為 .pdf 格式的文件下載到瀏覽器?
我已經嘗試過的:
res.set('Content-Disposition', 'attachment; filename="filename.pdf"');
res.set('Content-Type', 'application/pdf');
res.write(fileBase64String, 'base64');
我最終首先解碼 pdf,然后將其作為二進制文件發送到瀏覽器,如下所示:
(為簡單起見,我在這里使用node-http
,但這些功能也可以在express
中使用)
const http = require('http');
http
.createServer(function(req, res) {
getEncodedPDF(function(encodedPDF) {
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="filename.pdf"'
});
const download = Buffer.from(encodedPDF.toString('utf-8'), 'base64');
res.end(download);
});
})
.listen(1337);
讓我發瘋的是Postman的測試:
我使用發送按鈕而不是發送和下載按鈕來提交請求:
為此請求使用“發送”按鈕會導致 pdf 文件在保存后損壞。
只是Express
的參考。 這個答案基於 ofhouse 的答案。
此解決方案正在下載 png 文件。 我錯過了“內容處理”部分,這使得瀏覽器不顯示 png,而是下載它。 png
是一個Buffer
。
app.get("/image", (req, res) => {
getPng()
.then((png) => {
res.writeHead(200, {
"Content-Type": png.ContentType,
"Content-Length": png.ContentLength,
"Content-Disposition": 'attachment; filename="image.png"',
});
res.end(png.Body);
})
.catch(() => {
res.send("Couldn't load the image.");
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.