-
-
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 file contains 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
// 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