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.dispatchEvent
overa.click
since some browsers don't start the download whena.click
is called.
Without JavaScript
html
<a href="{{url}}" download="{{fileName}}">Click me to download!</a>
Warning
- The
url
must point to a resource on the same domain and should only contain the path. e.g. if the domain you're on issoorria.com
to downloadhttps://soorria.com/og.png
, theurl
should be/og.png