Downloading Files with Custom Filenames Using Data URIs
Data URIs provide a convenient way to embed data within web pages. However, when downloading data from a data URI, browsers typically prompt the user for a filename. Is it possible to provide a suggested filename in the markup or implement a JavaScript solution?
The download Attribute
Modern browsers support the "download" attribute for anchor () elements. This attribute allows you to specify a suggested filename for the downloaded file.
<a download="FileName" href="data:application/octet-stream;base64,SGVsbG8="> Download </a>
This solution works on Chrome, Firefox, Edge, Opera, desktop Safari 10 , iOS Safari 13 , but not IE11.
JavaScript Solution
If the "download" attribute is not supported, you can use a JavaScript solution:
const link = document.createElement("a"); link.setAttribute("href", "data:application/octet-stream;base64,SGVsbG8="); link.setAttribute("download", "FileName"); link.click();
This code creates an anchor element, sets the "href" and "download" attributes, and then simulates a click event to trigger the download.
The above is the detailed content of How Can I Download Files with Custom Filenames Using Data URIs?. For more information, please follow other related articles on the PHP Chinese website!