Skip to content

Instantly share code, notes, and snippets.

@image72
Forked from javilobo8/download-file.js
Last active April 28, 2020 09:19
Show Gist options
  • Save image72/065c7320199cf44ef2f72e593091c413 to your computer and use it in GitHub Desktop.
Save image72/065c7320199cf44ef2f72e593091c413 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();
});
function download(url, filename) {
fetch(url).then(function (t) {
return t.blob().then((b) => {
var a = document.createElement("a");
a.href = URL.createObjectURL(b);
a.setAttribute("download", filename);
a.click();
});
});
}
const downloadContent = (raw) => {
const url = window.URL.createObjectURL(new Blob([raw]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", `${+new Date()}.txt`);
document.body.appendChild(link);
link.click();
}
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment