Downloading Data From localStorage
12 March 2013
Lately i've been working extensively on a project which includes localStorage. I hit a small problem regarding how an end user can recover
thier data from localStorage. This would be useful if the user ever wanted to transfer their data to a new computer or browser.
Data URI's
I stumbled on a very hackey elegant way to download the data through the use of data URI's. These allow you to embed small files inline in documents. Give it a go below.
// create a fake object
var myData = {
'a': 'a',
'b': 'b',
'c': 'c'
};
// add it to our localstorage
localStorage.setItem('data', JSON.stringify(myData));
// encode the data into base64
base64 = window.btoa(localStorage.getItem('data'));
// create an a tag
var a = document.createElement('a');
a.href = 'data:application/octet-stream;base64,' + base64;
a.innerHTML = 'Download';
// add to the body
document.body.appendChild(a);
You could easily pair this with the FileReader object to read the files back in.