Download/Save file in react js

25,310

Solution 1

Here's how I usually handle this:

I start out by fetching the file and then use downloadjs to download the blob

async downloadFile() {
  const res = await fetch("https://mydomain.dev.com/export");
  const blob = res.blob();

  // from downloadjs it will download your file
  download(blob, "file.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");  
}

Solution 2

I always use this script to do this:

 function downloadFile(absoluteUrl) {
    var link = document.createElement('a');
    link.href = absoluteUrl;
    link.download = 'true';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    delete link;
 };

So just :

downloadFile("https://mydomain.dev.com/export");

It is working, but i hope that there is better solution.

Share:
25,310
Parashuram
Author by

Parashuram

Updated on July 09, 2022

Comments

  • Parashuram
    Parashuram almost 2 years

    How can i save the response from api which gives me excel file with data and name ?

    I have below api which gives me the excel file and i have to save it at default location as is.

    https://mydomain.dev.com/export
    

    I have gone through the multiple articles on the web but everywhere its explained to save the data as excel file at client side which is not the my case. For me, file type and name is already decided at server side and i have to just save as is.

    Thanks a lot in advance