Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Download files with AJAX (axios)
axios({
url: 'http://localhost:5000/static/example.pdf',
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');
link.click();
window.URL.revokeObjectURL(url);
});
@chaymag

This comment has been minimized.

Copy link

chaymag commented Aug 10, 2018

Thank you!

@myselfsum

This comment has been minimized.

Copy link

myselfsum commented Dec 25, 2018

Thanks. But how can I download any file from a full url using axios?

@steveclarke

This comment has been minimized.

Copy link

steveclarke commented Oct 15, 2019

If you'd prefer to have the document open in another tab inline use the following.

The important part is removing the download attribute and adding the type option when creating the Blob.

axios({
  url: 'http://localhost:5000/static/example.pdf',
  method: 'GET',
  responseType: 'blob', // important
}).then((response) => {
  const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/pdf' }));
  const link = document.createElement('a');
  link.href = url;
  link.target = '_blank'
  link.click();
  window.URL.revokeObjectURL(url);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.