Skip to content

Instantly share code, notes, and snippets.

@alvarosacari
Last active December 27, 2019 16:35
Show Gist options
  • Save alvarosacari/911917a809d8dc5187be04d08db21c8b to your computer and use it in GitHub Desktop.
Save alvarosacari/911917a809d8dc5187be04d08db21c8b to your computer and use it in GitHub Desktop.
download files with axios

Download files with axios

Example with blob

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

Example without blob

  axios({
    url: 'http://api.dev/file-download',
    method: 'GET',
  })
    .then(response => {
      // response.data.data = {
      //   url_file: 'https://domain.com/uploads/file_name.pdf'
      // }

      const url = response.data.data.url_file
      const name = url.split('/').reverse()[0]
      const link = document.createElement('a')

      link.href = url
      link.setAttribute('download', name)
      document.body.appendChild(link)
      link.click()
    })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment