How to send a pdf file from Node/Express app to the browser

后端 未结 5 2050
悲&欢浪女
悲&欢浪女 2020-12-06 00:06

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.createReadStrea         


        
5条回答
  •  广开言路
    2020-12-06 00:56

    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.

提交回复
热议问题