Home > Web Front-end > JS Tutorial > How Can I Control the Filename When Downloading Blobs in JavaScript?

How Can I Control the Filename When Downloading Blobs in JavaScript?

DDD
Release: 2024-12-09 12:23:14
Original
759 people have browsed it

How Can I Control the Filename When Downloading Blobs in JavaScript?

Custom Filename for Blob Downloads in JavaScript

When forcefully downloading a blob file via window.location, the assigned filename can be a random string. To customize this filename, a workaround involving a hidden element is employed.

Implementation

FileSaver.js provides an approach that involves:

  1. Creating a hidden element.
  2. Setting its href attribute to the blob's URL.
  3. Setting its download attribute to the desired filename.
  4. Clicking on the element.

Example

The following simplified example illustrates the technique:

var saveData = (function () {
  var a = document.createElement("a");
  document.body.appendChild(a);
  a.style = "display: none";
  return function (data, fileName) {
    var json = JSON.stringify(data),
      blob = new Blob([json], { type: "octet/stream" }),
      url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
  };
}());

var data = { x: 42, s: "hello, world", d: new Date() },
  fileName = "my-download.json";

saveData(data, fileName);
Copy after login

Notes

  • Older browsers may not support the download attribute.
  • Certain file formats may be considered insecure and trigger download failures. Saving JSON files with a .txt extension is recommended.

The above is the detailed content of How Can I Control the Filename When Downloading Blobs in JavaScript?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template