【问题标题】:Express.js - how to download base64 string as PDF file?Express.js - 如何将 base64 字符串下载为 PDF 文件?
【发布时间】:2015-04-18 13:56:09
【问题描述】:

我将 pdf 文件编码为 base64 字符串。如何将此字符串作为 .pdf 格式的文件下载到浏览器?

我已经尝试过的:

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

res.write(fileBase64String, 'base64');

【问题讨论】:

  • 与其使用一堆额外的流,不如直接使用res.write(fileBase64String, 'base64')
  • 是的,谢谢,更新了问题:) 我可以在客户端看到响应状态正常,但文件永远不会被保存。
  • 如果这就是你写的全部内容,请使用res.end(fileBase64String, 'base64'),它会写入数据并关闭响应。

标签: node.js file express stream base64


【解决方案1】:

我最终先解码了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:
的测试 我使用 Send 按钮而不是 Send and Download Button 来提交请求:

对该请求使用发送按钮会导致pdf文件在保存后损坏。

【讨论】:

    【解决方案2】:

    仅供参考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.");
          });
    });
    

    【讨论】:

      猜你喜欢
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      相关资源
      最近更新 更多