Setting Blob File Name for Forced Downloads in JavaScript
When downloading a blob file directly through window.location, the default filename is a random string. However, you may want to set a custom filename to make it more informative.
To achieve this, you can't rely solely on the window.location method. Instead, you'll need to use the following steps:
Here's an example that simplifies the process:
const saveData = (function () { const a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; return (data, fileName) => { const json = JSON.stringify(data); const blob = new Blob([json], { type: "octet/stream" }); const url = window.URL.createObjectURL(blob); a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); }; })(); const data = { x: 42, s: "hello, world", d: new Date() }; const fileName = "my-download.json"; saveData(data, fileName);
Notes:
The above is the detailed content of How Can I Force a Specific Filename When Downloading a Blob File in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!