React download files on button click

Total
0
Shares

React download files on button click using temporary anchor tag. It is helpful in case when you are getting binary data from a link. This binary file could be pdf, image, excel, word document, text or anything else. Fetch the link using Axios or javascript fetch api and download file with this code –

axios({
  method: "get",
  url: "downloadSamplePDF.php",
  responseType: "arraybuffer"
})
  .then((response) => {
    var link = document.createElement("a");
    link.href = window.URL.createObjectURL(
      new Blob([response.data], { type: "application/octet-stream" })
    );
    link.download = "name_of_file_with_extension";

    document.body.appendChild(link);

    link.click();
    setTimeout(function () {
      window.URL.revokeObjectURL(link);
    }, 200);
  })
  .catch((error) => {});

    Tweet this to help others

You might have to take care of CORS errors if you are dealing with cross origin requests. The downloadSamplePDF.php file will return the binary data. Also provide the name of file with extension in link.download.