Skip to content

Instantly share code, notes, and snippets.

@jasco
Last active April 2, 2020 07:48
Show Gist options
  • Save jasco/66e9f3b2b38f94728de60c781a223043 to your computer and use it in GitHub Desktop.
Save jasco/66e9f3b2b38f94728de60c781a223043 to your computer and use it in GitHub Desktop.
Browser download from fetched data
// Most samples used createObjectURL which gave errors suggesting no longer supported by the browser.
// This implementation encodes as a base64 string and saves as an octet-stream.
// Adapted from https://stackoverflow.com/a/38384008 and https://stackoverflow.com/a/11562550
function download(filename, arrayBuffer) {
const element = document.createElement('a');
const base64String = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));
element.setAttribute('href', 'data:application/octet-stream;base64,' + base64String);
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
function fetchForDownload(url, payload, filename) {
fetch(url, {
method: 'POST',
body: payload,
}).then((response) => response.arrayBuffer())
.then((data) => download(filename, data))
.catch((err) => console.error(err));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment