Express.js - 如何将base64字符串下载为PDF文件?

17

我有一个以Base64字符串编码的PDF文件。如何将此字符串作为.pdf格式的文件下载到浏览器中?

我已经尝试过的方法:

res.set('Content-Disposition', 'attachment; filename="filename.pdf"');
res.set('Content-Type', 'application/pdf');

res.write(fileBase64String, 'base64');

为什么不直接使用 res.write(fileBase64String, 'base64'),而要使用一堆额外的流呢? - mscdex
好的,谢谢,已经更新了问题 :) 我能在客户端看到响应状态是OK的,但文件从未被保存。 - Tomas
3
如果你只是要写这个,使用res.end(fileBase64String, 'base64'),它将同时写入数据并关闭响应。 - mscdex
2个回答

20

我最终首先解码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进行测试:
我使用了发送按钮而不是发送并下载按钮来提交请求:enter image description here

对于此请求,使用发送按钮会导致保存后的pdf文件损坏。


0

这是关于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.");
      });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接