JavaScript save blob to localStorage

a 夏天 提交于 2020-01-01 09:56:30

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/21008732/javascript-save-blob-to-localstorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!