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.

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like

React convert JSON to CSV

React convert JSON to CSV using JSONToCSVConvertor function. Suppose you have a table (GUI react table tool) and you want to export it into excel, then this function will come…
View Post