Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript save blob to localStorage

I am trying to save blob data (favicon) retrieved via AJAX, to localStorage.

Code :

var xhr = new XMLHttpRequest();
xhr.open('GET', 
'http://g.etfv.co/http://www.google.com',
true);
xhr.responseType = "blob";
xhr.onload = function(e){ //Stringify blob...
    localStorage['icon'] = JSON.stringify(xhr.response);
    //reload the icon from storage
    var fr = new FileReader();
    fr.onload = 
        function(e) {
            document.getElementById("myicon").src = fr.result;
        }
    fr.readAsDataURL(JSON.parse(localStorage['icon']));
    }
xhr.send(null);

The code is adapted from here with minor modifications to make it work with localStorage. localStorage saves all data as strings, so blobs need to be stringified somehow before being saved.

JSON doesn't deal with blobs as one of it's supported types, so it's no surprise that this code fails.

Is there any way to get the blob into localStorage?

like image 548
MadeOfAir Avatar asked Jan 08 '14 23:01

MadeOfAir


People also ask

Can I store blob in localStorage?

You can store Blobs in LocalStorage as base64 strings, which is really inefficient.

How do I save a blob in local file system?

Saving BLOB as File using JavaScript Then inside the onload event handler, the received Byte Array (Binary Data) is converted to BLOB object and the File is downloaded in Browser. //Set the File URL. var url = "Files/" + fileName; //Create XMLHTTP Request.

Can I store file in localStorage?

localStorage can only store Strings, while modern Javascript can also handle binary files. For example, the result of a fetch can be retrieved as a Blob .


1 Answers

Just store the blob as a data uri in local storage

var xhr = new XMLHttpRequest();
xhr.open('GET', 
'http://g.etfv.co/http://www.google.com',
true);
xhr.responseType = "blob";
xhr.onload = function(e){ //Stringify blob...
    //reload the icon from storage
    var fr = new FileReader();
    fr.onload = 
        function(e) {
            localStorage['icon'] = e.target.result;
            document.getElementById("myicon").src = localStorage['icon'];
        }
    fr.readAsDataURL(xhr.response);
}
xhr.send(null);
like image 140
Musa Avatar answered Sep 20 '22 00:09

Musa