Home >Web Front-end >JS Tutorial >How to Set a Custom File Name for Blob Downloads in JavaScript?

How to Set a Custom File Name for Blob Downloads in JavaScript?

DDD
DDDOriginal
2024-12-05 13:45:11894browse

How to Set a Custom File Name for Blob Downloads in JavaScript?

Setting Custom Blob File Name in JavaScript

When working with blobs in JavaScript, you may encounter a situation where you need to specify a custom file name instead of the default randomly generated one. This is particularly useful when you want to provide a meaningful file name for downloads or data exports.

Problem: Assigning Custom Blob File Name

The following code snippet creates a blob and attempts to download it through window.location, but the downloaded file has a random name like "bfefe410-8d9c-4883-86c5-d76c50a24a1d":

function newFile(data) {
    var json = JSON.stringify(data);
    var blob = new Blob([json], {type: "octet/stream"});
    var url = window.URL.createObjectURL(blob);
    window.location.assign(url);
}

Solution: Using the A Tag Trick

The only known method to assign a custom file name to a blob in JavaScript involves a trick using a hidden tag:

  1. Create a hidden tag.
  2. Set its href attribute to the blob's URL.
  3. Set its download attribute to the desired file name.
  4. Click on the tag programmatically.

Example Code:

The following example demonstrates how to use this trick to save a JSON object to a file with the name "my-download.json":

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

Notes:

  • Older browsers may not support the download attribute.
  • Certain file formats may not be supported by the browser and may result in a download failure. For example, saving JSON files with a .txt extension has been observed to work.

The above is the detailed content of How to Set a Custom File Name for Blob Downloads 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