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
Susan SarandonOriginal
2024-11-28 00:19:10454browse

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;
}

An example of its usage:

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

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!

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