Question
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?
Answer
`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);
});`
This answer was originally posted on Stack Overflow. You can find the full discussion here