Sending pdf files to user from nodejs to reactjs

Viewed 6028

I have pdf documents stored in the file system on the server side.

I need to let the user download one of them when he/she clicks on download.

The problem is that I know how to send a file from NodeJS to browser but here the request will be made by a ReactJS axios request. So when I send a file, the response will go to react. How do I send that pdf file to the user? Do I access the file system directly using my front end code?

I get the following in the browser console when I log the response after I do res.sendFile(file_path) in NodeJS

enter image description here

How do I process this so that I can make the user download the pdf?

1 Answers

You can use file-saver to download the file. Below is the function I'm using for pdf download. (response.data is the Buffer that nodejs sends back as a response)

import FileSaver from 'file-saver';
...

_onPdfFetched() {
  FileSaver.saveAs(
    new Blob([response.data], { type: 'application/pdf' }),
    `sample.pdf`
  );
}

or you can just show pdf to the user

window.open(response.data, '_blank');

Edit

The axios call should be like this:

axios.get(url, {
  responseType: 'arraybuffer',
  headers: {
      Accept: 'application/pdf',
  },
});

Edit 2

The nodejs code should be like this:

router.post('/api/downloadfile',(req, res, next) => {
  const src = fs.createReadStream('path to sample.pdf');

  res.writeHead(200, {
    'Content-Type': 'application/pdf',
    'Content-Disposition': 'attachment; filename=sample.pdf',
    'Content-Transfer-Encoding': 'Binary'
  });

  src.pipe(res); 
});
Related