Last active
April 24, 2025 13:41
-
-
Save Lehoczky/241f046b05c54af65918676888fc783f to your computer and use it in GitHub Desktop.
Downloading a file in 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
/** | |
* Opens the user's system file dialog prompting to download | |
* the given data. | |
* | |
* @param fileName default name of the saved file. This is what will show up as file name in the user's file dialog. | |
* @param data the content of the file. | |
* @param mime [mime type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) of the file | |
* @param bom | |
*/ | |
export function download( | |
fileName: string, | |
data: string | ArrayBuffer | ArrayBufferView | Blob, | |
mime = "text/plain", | |
bom?: string | Uint8Array, | |
) { | |
const blobData = bom === undefined ? [data] : [bom, data] | |
const blob = new Blob(blobData, { type: mime }) | |
const a = document.createElement("a") | |
a.download = fileName | |
a.href = URL.createObjectURL(blob) | |
a.click() | |
setTimeout(() => { | |
URL.revokeObjectURL(a.href) | |
a.remove() | |
}, 200) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment