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'))
}

Info

  • We use a.dispatchEvent over a.click since some browsers don't start the download when a.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 is soorria.com to download https://soorria.com/og.png, the url should be /og.png

Demo

Download An Image (No JS)
Created 04/26/22Updated 10/13/22
Found a mistake, or want to suggest an improvement? Edit on GitHub here
and see edit history here