How to Create a Download Link in HTML?

Find out how you can create a download link using HTML

You can use the HTML5 download attribute on an <a> (anchor) element which would prompt the user to save the linked resource instead of navigating to it. However, you must note that it will only work in the following cases:

  1. same-origin resource, or;
  2. URL with blob: scheme, or;
  3. URL with data: scheme.

For example, you can use an origin-relative URL like so:

<a href="/path/to/image.jpg" download>Download</a>

Or, a blob/data scheme resource like so:

<a
    href="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
    download
>
    Download
</a>

You could also, optionally, specify a value for the download attribute which would be used as the file name:

<a href="/path/to/image.jpg" download="foo.jpg">Download</a>

Please note that some browsers might not honor the suggested filename in the download attribute for cross-origin requests.

Based on the code above, the filename will be foo.jpg instead of image.jpg. Another thing to note here is that, you may safely omit the file extension. When no filename or file extension is specified in the attribute, the browser will suggest a filename/extension, generated from the following:

  • The Content-Disposition HTTP header;
  • The final part of the URL path;
  • The media type (such as from the Content-Type header, the start of a data: URL, or Blob.type for a blob: URL).

For example, the following would result in the filename "foo.jpg" (where the file extension is derived from the URL path):

<a href="/path/to/image.jpg" download="foo">Download</a>

Please note that, if the filename has the characters "/" and "\", they will be converted to underscores (_). Additionally, browsers may adjust the suggested filename if it contains characters that the filesystem forbids.

The presence of the Content-Disposition header may affect the behavior of the download attribute in the following scenarios:

  • If the header specifies a filename, it would take precedence over the filename (if any) specified in the download attribute;
  • If the header specifies a disposition of inline, some browsers (such as Chrome & Firefox 82+) may prioritize the download attribute and treat it as a download, while others may prioritize the header and display the content inline.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.