Express应用程序向浏览器发送pdf文件

Express应用程序向浏览器发送pdf文件

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

问题描述

在我的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?

推荐答案

您必须从可读流到可写流进行管道传输,而不是相反:

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.

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

08-13 22:30