Explain Codes LogoExplain Codes Logo

Is there any way to specify a suggested filename when using data: URI?

html
download-attribute
data-uri
javascript-workaround
Alex KataevbyAlex Kataev·Aug 21, 2024
TLDR
<a href="data:text/plain;charset=utf-8,Hello%20World" download="hello.txt">Download</a>

With the download attribute within an <a> tag, you can specify a suggested filename for a data URI download.

We implement the suggested filename for a data URI download using the HTML5 download attribute. This attribute is placed inside an anchor tag (<a>), and is recognized and accepted by modern browsers such as Chrome, Firefox, Edge, Opera, and Safari 10+.

However, for browsers like IE11 & older versions of Edge and Safari which lack support for this attribute, an alternative approach would be to use JavaScript to create a link with the desired data URI, then simulate a click event to initiate the download.

It's important to specify the correct mime type for data URIs so they're interpreted and handled properly by the browser. Also, remember to clean up after the download process, especially if you're using JavaScript to dynamically insert link elements into your document.

For a smooth user experience, always provide an alternative mechanism for downloading the file if the download attribute is unsupported by the browser.

Implementing the download attribute

For a specified filename to be downloaded, the download attribute can be added to the anchor (<a>) tags like this:

<a href="data:text/plain;charset=utf-8,Hello%20Java" download="no_coffee.Java">Where's my coffee?!? ☕</a>

This attribute works for Chrome, Firefox, Edge, Opera, and desktop Safari 10+, as well as iOS Safari 13+. However, it's not supported in IE11 and older versions of Edge and Safari.

Using the download attribute provides a JavaScript-independent solution for naming your downloads. It understands the protocols of the data: URI scheme, and thus can be effectively used with it.

A JavaScript Workaround for Unsupported Browsers

For those browsers that don't support the download attribute, we can simulate a click event on the anchor tag using JavaScript. Here's a simple function that accomplishes this:

function downloadDataURI(uri, filename) { var link = document.createElement("a"); link.download = filename; link.href = uri; // Sneaky sneaky trick to initiate a download, don't tell my grandma, she thinks I'm angel 👼 document.body.appendChild(link); link.click(); document.body.removeChild(link); // Clean up after yourself, your mom doesn't work in the browser! } // Use the function like this: downloadDataURI("data:text/plain;charset=utf-8,Hello%20World", "hello.txt");