Home >Web Front-end >JS Tutorial >How Can I Download Files with Custom Filenames Using Data URIs?

How Can I Download Files with Custom Filenames Using Data URIs?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 05:22:17215browse

How Can I Download Files with Custom Filenames Using Data URIs?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn