Skip to content

Instantly share code, notes, and snippets.

@thomaskonrad
Created February 8, 2020 16:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save thomaskonrad/37772256a86d9f5b0472b3c2440cffee to your computer and use it in GitHub Desktop.
Save thomaskonrad/37772256a86d9f5b0472b3c2440cffee to your computer and use it in GitHub Desktop.
Downloading an Array Buffer via a "Save as" Dialog in the Browser
// This source code is taken from Firefox Send (https://github.com/mozilla/send) and slightly modified.
export default async function saveFile(plaintext: ArrayBuffer, fileName: string, fileType: string) {
return new Promise((resolve, reject) => {
const dataView = new DataView(plaintext);
const blob = new Blob([dataView], { type: fileType });
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, fileName);
return resolve();
} else if (/iPhone|fxios/i.test(navigator.userAgent)) {
// This method is much slower but createObjectURL
// is buggy on iOS
const reader = new FileReader();
reader.addEventListener('loadend', () => {
if (reader.error) {
return reject(reader.error);
}
if (reader.result) {
const a = document.createElement('a');
// @ts-ignore
a.href = reader.result;
a.download = fileName;
document.body.appendChild(a);
a.click();
}
resolve();
});
reader.readAsDataURL(blob);
} else {
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = downloadUrl;
a.download = fileName;
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(downloadUrl);
setTimeout(resolve, 100);
}
});
}
@angstyloop
Copy link

angstyloop commented Feb 23, 2023

forked! had to make a couple changes to make the typescript compiler happy, plus a few small additional changes

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