File Downloads
Download a file, text, blob, etc programmatically with JavaScript, or download from a url without JavaScript
With JavaScript
typescriptjavascript
export const download = (
content: string | Blob | File,
fileName: string,
type?: string
) => {
const blob =
typeof content === 'string' ? new Blob([content], { type }) : content
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = fileName
a.rel = 'noopener'
a.dispatchEvent(new MouseEvent('click'))
}export const download = (content, fileName, type) => {
const blob =
typeof content === 'string' ? new Blob([content], { type }) : content
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = fileName
a.rel = 'noopener'
a.dispatchEvent(new MouseEvent('click'))
}
Info
- We use
a.dispatchEventovera.clicksince some browsers don't start the download whena.clickis called.
Without JavaScript
html
<a href="{{url}}" download="{{fileName}}">Click me to download!</a>Warning
- The
urlmust point to a resource on the same domain and should only contain the path. e.g. if the domain you're on issoorria.comto downloadhttps://soorria.com/og.png, theurlshould be/og.png
Demo
Created 26/04/22 • Updated 13/10/22