The only way I'm aware of is the trick used by FileSaver.js:
- Create a hidden
<a>
tag.
- Set its
href
attribute to the blob's URL.
- Set its
download
attribute to the filename.
- Click on the
<a>
tag.
Here is a simplified example (jsfiddle):
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);
I wrote this example just to illustrate the idea, in production code use FileSaver.js instead.
Notes
- Older browsers don't support the "download" attribute, since it's part of HTML5.
- Some file formats are considered insecure by the browser and the download fails. Saving JSON files with txt extension works for me.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…