如何将 pdf 文件从 Node/Express 应用程序发送到浏览器 [英] How to send a pdf file from Node/Express app to the browser

查看:26
本文介绍了如何将 pdf 文件从 Node/Express 应用程序发送到浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Node/Express 应用程序中,我有以下代码,假设从文件中读取 PDF 文档,并将其发送到浏览器:

In my Node/Express app I have the following code, which suppose to read a PDF document from a file, and send it to the browser:

var file = fs.createReadStream('./public/modules/datacollectors/output.pdf', 'binary');
var stat = fs.statSync('./public/modules/datacollectors/output.pdf');
res.setHeader('Content-Length', stat.size);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename=quote.pdf');
res.pipe(file, 'binary');
res.end(); 

我没有收到任何错误,但我的浏览器中也没有收到该文件.我做错了什么?

I do not get any errors, but I do not get the file in my browser either. What am I doing wrong?

推荐答案

你必须从 Readable Stream 到 Writable 流进行管道传输,而不是相反:

You have to pipe from Readable Stream to Writable stream not the other way around:

var file = fs.createReadStream('./public/modules/datacollectors/output.pdf');
var stat = fs.statSync('./public/modules/datacollectors/output.pdf');
res.setHeader('Content-Length', stat.size);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename=quote.pdf');
file.pipe(res);

此外,您还以错误的方式设置编码,如果需要,请传递带有编码的对象.

Also you are setting encoding in wrong way, pass an object with encoding if needed.

这篇关于如何将 pdf 文件从 Node/Express 应用程序发送到浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆