React download a pdf file from Node and open it in a tab

I managed to get my upload to the server functionality work, however I am struggling with the download from the server.

I successfuly receive the file from the server, however I have no idea how to download it as a file or open it in a new tab (preferably).

So on the front end I have, a Link element with onClick that sends the request:

<Link
  onClick={(e) => {
    handleDownloadInvoice(e, invoice.scannedFileName);
  }}
  href={``}
>

and the handling function in react:

const handleDownloadInvoice = async (e, fileName) => {
  e.preventDefault();

  const invoiceFile = await axios.get(`http://localhost:3000/api/v1/invoice/getfile/${fileName}`, {
    headers: { "x-access-token": localStorage.getItem("token") },
  });

  console.log(invoiceFile);
};

From the server:

const getScannedFile = async (req, res) => {
  const { fileName } = req.params;

  res.contentType("application/pdf").sendFile(__basedir + `\\uploadedFiles\\invoices\\${fileName}`);
};

So the logged invoiceFile has the data as a string, and it has the correct header: {content-type: "application/pdf" }

The question is, how do I transform this data string back to a pdf file that either gets opened in a tab (preferably) or gets downloaded as a file to the clients computer?



Read more here: https://stackoverflow.com/questions/65726898/react-download-a-pdf-file-from-node-and-open-it-in-a-tab

Content Attribution

This content was originally published by Darkbound at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: