Home >Web Front-end >JS Tutorial >How Can I Customize Blob Filenames When Downloading Directly in JavaScript?

How Can I Customize Blob Filenames When Downloading Directly in JavaScript?

DDD
DDDOriginal
2024-12-26 22:38:10255browse

How Can I Customize Blob Filenames When Downloading Directly in JavaScript?

Customizing Blob Filename for Direct Downloads in JavaScript

Introduction

When using window.location to force download a blob file in JavaScript, the downloaded file's name is automatically generated. To customize this filename, additional steps are required.

Solution with FileSaver.js Trick

One workaround involves utilizing a technique similar to the one employed by FileSaver.js:

  1. Create a hidden tag.
  2. Assign the blob's URL to the href attribute.
  3. Set the desired filename using the download attribute.
  4. Initiate the download by clicking on the tag.

Simplified Example

function saveData(data, fileName) {
  var json = JSON.stringify(data),
      blob = new Blob([json], {type: "octet/stream"}),
      url = window.URL.createObjectURL(blob);
  var a = document.createElement("a");
  document.body.appendChild(a);
  a.style = "display: none";
  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);

Usage of FileSaver.js

While the above method can work, it is recommended to use the more robust FileSaver.js library for file saving in JavaScript:

import { saveAs } from 'file-saver';

var json = JSON.stringify(data),
    filename = "my-download.json";

var blob = new Blob([json], {type: "octet/stream"});
saveAs(blob, filename);

Considerations

  • Older browsers may not support the download attribute, as it is an HTML5 feature.
  • Certain file formats may be considered insecure and block the download. Saving JSON files with the .txt extension can mitigate this issue.

The above is the detailed content of How Can I Customize Blob Filenames When Downloading Directly in JavaScript?. 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