Skip to content

Instantly share code, notes, and snippets.

@iampaul83
Forked from javilobo8/download-file.js
Last active January 21, 2019 09:46
Show Gist options
  • Save iampaul83/3f435b5a00aa931e2bc3b6f6742e673e to your computer and use it in GitHub Desktop.
Save iampaul83/3f435b5a00aa931e2bc3b6f6742e673e to your computer and use it in GitHub Desktop.
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');
document.body.appendChild(link);
link.click();
});
const triggerDownload = (filename, blob) => {
// ie
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
return window.navigator.msSaveOrOpenBlob(blob, filename)
}
// Chome, Firefox, ....
const object_url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = object_url
a.download = filename
a.click()
a.remove()
URL.revokeObjectURL(object_url)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment