Express.js – 如何将base64string下载为PDF文件?
我有PDF文件编码为base64string。 如何以.pdf格式将此string下载到浏览器中?
我已经试过了:
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);
让我疯狂的是邮差testing:
我使用发送button而不是发送和下载 button来提交请求:
但是使用这个请求的发送button会导致pdf文件在保存之后被破坏。