Skip to content

Instantly share code, notes, and snippets.

@angstyloop
Forked from thomaskonrad/saveFile.ts
Last active February 23, 2023 06:51
Show Gist options
  • Save angstyloop/f7b0e5056c276aff0640e8c5bdd703d9 to your computer and use it in GitHub Desktop.
Save angstyloop/f7b0e5056c276aff0640e8c5bdd703d9 to your computer and use it in GitHub Desktop.
Downloading a binary file and saving the file by name in the browser with TypeScript
declare global {
interface Navigator {
msSaveBlob?: (blob: any, defaultName?: string) => boolean
}
}
export default async function saveFile(arrayBuffers: ArrayBuffer[], fileName: string, fileType: string): Promise<void> {
return new Promise((resolve, reject) => {
const blob = new Blob(arrayBuffers, { type: fileType });
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, fileName);
resolve();
} else if (/iPhone|fxios/i.test(navigator.userAgent)) {
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