Home >Web Front-end >JS Tutorial >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:
var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none";
a.href = url; a.download = "my-download.json";
a.click();
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:
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!