I read few older thread about the same, but seen the file API changed a lot recently. My requirement is to save a json file (data is locally in indexdDB, but I need a way to back it up). Since I use indexdDB, I only target recent browsers, mainly chrome. So, it it possible to save data (json string) to client computer?
I have seen http://eligrey.com/demos/FileSaver.js/ , but is there a way to do it natively?
Thanks.
Advertisement
Answer
You can use a Blob
and the HTML5 a[download]
feature to provide a JSON backup download:
JavaScript
x
10
10
1
var data = {a:1, b:2, c:3};
2
var json = JSON.stringify(data);
3
var blob = new Blob([json], {type: "application/json"});
4
var url = URL.createObjectURL(blob);
5
6
var a = document.createElement('a');
7
a.download = "backup.json";
8
a.href = url;
9
a.textContent = "Download backup.json";
10
Here is a jsfiddle example: http://jsfiddle.net/potatosalad/yuM2N/