Download Files with Axios

You must be familiar with axios calls for API consumption, but what about getting the files in response and render those files to the user for download. We got your covered, the below snippet is tested and works well.

You must be familiar with axios calls for API consumption, but what about getting the files in response and render those files to the user for download. We got your covered, the below snippet is tested and works well.

axios({
  url: 'http://api.dev/file-download',
  method: 'GET',
  responseType: 'blob', // important
}).then((response) => {
   const url = window.URL.createObjectURL(new Blob([response.data]));
   const link = document.createElement('a');
   link.href = url;
   link.setAttribute('download', 'file.pdf'); //or any other extension
   document.body.appendChild(link);
   link.click();
});

Credits to this Javilobo for his useful Gist.