-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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