Skip to content

Instantly share code, notes, and snippets.

@thenoobtester
Forked from thomaskonrad/saveFile.ts
Created October 12, 2024 14:20
Show Gist options
  • Save thenoobtester/e5cb978dae99149c53aa47f76e2af96a to your computer and use it in GitHub Desktop.
Save thenoobtester/e5cb978dae99149c53aa47f76e2af96a 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);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment