Home >Web Front-end >JS Tutorial >How to Set a Custom Filename When Downloading a Blob File in JavaScript?

How to Set a Custom Filename When Downloading a Blob File in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-13 18:46:10743browse

How to Set a Custom Filename When Downloading a Blob File in JavaScript?

JavaScript: Setting Filename for Blob File for Direct Download

When downloading a blob file in JavaScript using window.location, the file is typically saved with a generic name. To set a custom filename, it is necessary to employ a specific technique that involves creating a hidden tag.

In the original code example:

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

This code downloads a file named:

bfefe410-8d9c-4883-86c5-d76c50a24a1d

To set the filename as my-download.json, follow these steps:

  1. Create a hidden tag and append it to the document:
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
  1. Set the tag's href attribute to the blob's URL and download attribute to the desired filename:
a.href = url;
a.download = "my-download.json";
  1. Trigger the download by clicking on the tag:
a.click();
  1. Revoke the blob's URL to prevent it from being accessed again:
window.URL.revokeObjectURL(url);

Example Implementation:

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.
  • Some file formats (e.g., JSON) may need to be saved with a different extension (e.g., txt) to avoid security restrictions.
  • Consider using a library like FileSaver.js for a more robust and reliable solution.

The above is the detailed content of How to Set a Custom Filename When Downloading a Blob File 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