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:
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:
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!