Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Express.js-如何下载base64字符串作为PDF文件?_Node.js_File_Express_Stream_Base64 - Fatal编程技术网

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

Node.js Express.js-如何下载base64字符串作为PDF文件?,node.js,file,express,stream,base64,Node.js,File,Express,Stream,Base64,我将pdf文件编码为base64字符串。如何将此字符串作为.pdf格式的文件下载到浏览器 我已经尝试过的: res.set('Content-Disposition', 'attachment; filename="filename.pdf"'); res.set('Content-Type', 'application/pdf'); res.write(fileBase64String, 'base64'); 我首先对pdf进行解码,然后将其作为二进制文件发送到浏览器,如下所示: (为了简

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

我已经尝试过的:

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

res.write(fileBase64String, 'base64');

我首先对pdf进行解码,然后将其作为二进制文件发送到浏览器,如下所示:

(为了简单起见,我在这里使用
节点http
,但是
express
中也提供了这些函数)


让我抓狂的是测试:
我使用发送按钮而不是发送和下载来提交请求:


使用此请求的“发送”按钮会导致pdf文件在保存后损坏。

仅作为
Express
的参考。这个答案是基于House的答案

此解决方案正在下载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.");
      });
});

与其使用一堆额外的流,为什么不直接执行
res.write(fileBase64String,'base64')
?是的,谢谢,更新了问题:)我可以在客户端看到响应状态OK,但文件永远不会保存。如果您只编写了这些,请使用
res.end(fileBase64String,'base64')
,这将写入数据并关闭响应。
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.");
      });
});