Home > Web Front-end > JS Tutorial > How Can I Download Files from Data URLs in Different Browsers?

How Can I Download Files from Data URLs in Different Browsers?

Susan Sarandon
Release: 2024-11-28 00:19:10
Original
454 people have browsed it

How Can I Download Files from Data URLs in Different Browsers?

Downloading Files through Data URLs

In the pursuit of creating a JavaScript-based zip utility accessible through a browser, a crucial challenge arises: downloading files from data URLs. While Firefox handles it seamlessly, Chrome poses difficulties. Embracing data URLs for file downloads poses limitations, as files may not always be images.

A Workaround Solution

For Chrome, Firefox, and certain IE versions, a workaround exists. By leveraging the following code, users can provide a specific file name for the download:

function downloadURI(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  delete link;
}
Copy after login

An example of its usage:

downloadURI("data:text/html,HelloWorld!", "helloWorld.txt");
Copy after login

With this workaround, users can effortlessly download files with desired file names, regardless of their formats.

The above is the detailed content of How Can I Download Files from Data URLs in Different Browsers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template