Beyond the Generic: Controlling Downloaded Filenames for Data URIs in HTML and JavaScript
Specifying a Suggested Filename with Data URIs in JavaScript and HTML
Data URIs are a way to embed data directly within an HTML document. They consist of three parts:
- Data URI scheme:
data:
- MIME type: This specifies the type of data, like
image/png
for an image. - Encoded data: The actual data, usually Base64 encoded.
The Challenge:
Data URIs themselves don't carry information about the intended filename. This means when a user tries to download the content, the browser typically uses a generic filename based on the MIME type or simply displays the data in a new tab.
Solutions:
Here are two approaches to suggest a filename when using data URIs:
Using the download attribute (HTML):
This method works in modern browsers like Chrome, Firefox, and Edge (version 13+). It involves creating an anchor tag (<a>
) with the href
attribute set to the data URI and the download
attribute specifying the suggested filename.
<a href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=" download="my_image.png">Download Image</a>
When the user clicks this link, the browser will prompt them to save the file and use the suggested filename "my_image.png".
Using JavaScript and click simulation:
This approach works across various browsers but involves a bit more code. It utilizes JavaScript to create a temporary anchor element, set its properties, and simulate a click event.
function downloadURI(dataURI, filename) {
const link = document.createElement('a');
link.href = dataURI;
link.download = filename;
link.click();
}
// Usage example
const imageURI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
downloadURI(imageURI, "image_from_script.png");
This code defines a function downloadURI
that takes the data URI and desired filename as arguments. It creates a hidden anchor element, sets its href
to the data URI and download
attribute to the filename, and then triggers a click event using the click()
method.
javascript html url