Skip to content

Instantly share code, notes, and snippets.

@Tomassito
Forked from javilobo8/download-file.js
Last active March 11, 2022 23:53
Show Gist options
  • Save Tomassito/a5b4d29f459b9383dc3daa313ae5f73b to your computer and use it in GitHub Desktop.
Save Tomassito/a5b4d29f459b9383dc3daa313ae5f73b 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');
link.click();
window.URL.revokeObjectURL(url);
});
@thugcee
Copy link

thugcee commented Apr 5, 2020

To reuse the file name from content-disposition header:

    link.setAttribute('download', response.headers["content-disposition"].split("filename=")[1])

Don't forget about adding content-disposition to Access-Control-Expose-Headers when CORS rules apply.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment