Force download links in HTML

By

Published · Updated

Tagged: HTML

Learn how to force a file download in HTML by adding the download attribute to an a tag, so the browser saves the file instead of opening it in the tab.

I recently found out you can add the download attribute to an a tag:

<a href="file.pdf" download>pdf</a>

and the browser forces the download even if the file could be loaded in the browser (like a PDF).

This only works for links on the same origin.

When the server sends the file, the name comes from a Content-Disposition header.

Set the file name

Give download a value to suggest a file name:

<a href="/files/invoice-1042.pdf" download="invoice.pdf">Download the invoice</a>

The file is saved as invoice.pdf.

Without a value, the browser picks the name from the Content-Disposition header, then from the last part of the URL, and uses the Content-Type to guess the extension.

A few details about the name:

Same origin only

download only works for:

For a file on another domain, like a CDN or an S3 bucket, the browser ignores download and simply opens the link, as if the attribute wasn’t there. No error is shown.

There are two ways around it.

Set the header on the server. If you control the server that hosts the file, make it send:

Content-Disposition: attachment; filename="report.pdf"

The browser downloads the file from any link, with or without download. Many storage services, like S3, let you set this header on the file or on a signed URL.

Fetch the file and download the blob. If the other server allows your page to read the file with CORS (it sends Access-Control-Allow-Origin), you can fetch it and download a blob: URL, which is same origin:

async function downloadFile(url, filename) {
  const response = await fetch(url)
  if (!response.ok) throw new Error(`HTTP ${response.status}`)

  const blob = await response.blob()
  const blobUrl = URL.createObjectURL(blob)

  const a = document.createElement('a')
  a.href = blobUrl
  a.download = filename
  a.click()

  URL.revokeObjectURL(blobUrl)
}

downloadFile('https://cdn.example.com/report.pdf', 'report.pdf')

Without CORS the fetch() fails, and only the header approach works. Also, this loads the whole file in memory before saving it, so it’s not a good idea for very big files.

Download a file you create in JavaScript

The same trick works for data you generate in the page, like a CSV export:

function downloadCSV(rows, filename) {
  const csv = rows.map((row) => row.join(',')).join('\n')
  const blob = new Blob([csv], { type: 'text/csv' })
  const url = URL.createObjectURL(blob)

  const a = document.createElement('a')
  a.href = url
  a.download = filename
  a.click()

  URL.revokeObjectURL(url)
}

downloadCSV(
  [
    ['name', 'age'],
    ['Flavio', 37],
  ],
  'people.csv'
)

The link doesn’t need to be in the page, calling click() on it is enough. URL.revokeObjectURL() frees the memory used by the blob.

This simple join doesn’t handle values that contain commas or quotes. Wrap those values in double quotes, and double any quote inside them.

For small text, a data: URL works too:

const a = document.createElement('a')
a.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent('Hello!')
a.download = 'hello.txt'
a.click()

To save a <canvas> drawing as an image, use toDataURL():

const canvas = document.querySelector('canvas')
const a = document.createElement('a')
a.href = canvas.toDataURL('image/png')
a.download = 'drawing.png'
a.click()

download doesn’t always mean “save”

What happens after the click depends on the browser and its settings. The browser may ask where to save the file, save it right away to the Downloads folder, or open it after the download. You can’t control that from the page.

Want me to talk about your product? You can sponsor this site.

Related posts about html: