我有一个以Base64字符串编码的PDF文件。如何将此字符串作为.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文件。我错过了“Content-Disposition”部分,这使得浏览器不显示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.");
});
});
res.write(fileBase64String, 'base64')
,而要使用一堆额外的流呢? - mscdexres.end(fileBase64String, 'base64')
,它将同时写入数据并关闭响应。 - mscdex