Home >Web Front-end >JS Tutorial >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:
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);
Notes
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!