Home » excel » javascript – Download/Save file in react js

javascript – Download/Save file in react js

Posted by: admin April 23, 2020 Leave a comment

Questions:

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

How to&Answers:

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.

Answer:

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");  
}