Display Pdf in browser using express js

Viewed 77345

I'm trying to serve a PDF via Express in a way it is displayed in browser:

app.post('/asset', function(request, response){
  var tempFile="/home/applmgr/Desktop/123456.pdf";
  fs.readFile(tempFile, function (err,data){
     response.contentType("application/pdf");
     response.send(data);
  });
});

However, the browser shows binary content. How to handle this correctly?

7 Answers

Actually Express already has this feature for sending files. All you need is :

app.get('/sendMePDF', function(req, res) {
  res.sendFile(__dirname + "/static/pdf/Rabbi.pdf");
})

Here the server will send the file "Rabbi.pdf" and it will open in browser like you open pdf in browser. I placed the file in "static" folder but you can place it anywhere, knowing that sendFile() takes as argument the absolute path (not relative one).

According to Express js documentation you can set the Content Type and the Content Disposition all in one function as shown below

 fs.readFile(filePath, (err, data) => {
res.set({
  "Content-Type": "application/pdf", //here you set the content type to pdf
  "Content-Disposition": "inline; filename=" + fileName, //if you change from inline to attachment if forces the file to download but inline displays the file on the browser
});
res.send(data); // here we send the pdf file to the browser
});
post('/fileToSend/', async (req, res) => {

  const documentPath = path.join(
    __dirname,
    '../assets/documents/document.pdf'
  );
    
  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', 'attachment; filename=document.pdf');

  return res.download(documentPath);
});
Related