在我的 Node/Express 应用程序中,我有以下代码,假设从文件中读取 PDF 文档,并将其发送到浏览器:
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();
我没有收到任何错误,但我也没有在我的浏览器中获得该文件。 我做错了什么?
最佳答案
你必须从可读流到可写流,而不是相反:
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);
另外,如果您以错误的方式设置编码,请在需要时传递带有编码的对象。
关于node.js - 如何将 pdf 文件从 Node/Express 应用程序发送到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31105846/