Home >Web Front-end >JS Tutorial >How Can I Customize Blob Filenames When Downloading Directly in JavaScript?
Customizing Blob Filename for Direct Downloads in JavaScript
Introduction
When using window.location to force download a blob file in JavaScript, the downloaded file's name is automatically generated. To customize this filename, additional steps are required.
Solution with FileSaver.js Trick
One workaround involves utilizing a technique similar to the one employed by FileSaver.js:
Simplified Example
function saveData(data, fileName) { var json = JSON.stringify(data), blob = new Blob([json], {type: "octet/stream"}), url = window.URL.createObjectURL(blob); var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; 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);
Usage of FileSaver.js
While the above method can work, it is recommended to use the more robust FileSaver.js library for file saving in JavaScript:
import { saveAs } from 'file-saver'; var json = JSON.stringify(data), filename = "my-download.json"; var blob = new Blob([json], {type: "octet/stream"}); saveAs(blob, filename);
Considerations
The above is the detailed content of How Can I Customize Blob Filenames When Downloading Directly in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!