Skip to content

Instantly share code, notes, and snippets.

@Lehoczky
Last active April 24, 2025 13:41
Show Gist options
  • Save Lehoczky/241f046b05c54af65918676888fc783f to your computer and use it in GitHub Desktop.
Save Lehoczky/241f046b05c54af65918676888fc783f to your computer and use it in GitHub Desktop.
Downloading a file in TypeScript
/**
* 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