JavaScript将blob保存到localStorage

时间:2014-01-08 23:24:53

标签: javascript json html5 blob web-storage

我正在尝试将通过AJAX检索的blob数据(favicon)保存到localStorage

代码:

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

代码改编自here,稍作修改,以便与localStorage一起使用。 localStorage将所有数据保存为字符串,因此在保存之前,blob需要以某种方式字符串化

JSON不会将blob作为其支持类型之一处理,因此这段代码失败就不足为奇了。

有没有办法让blob进入localStorage?

1 个答案:

答案 0 :(得分:5)

只需将blob存储为本地存储中的数据uri

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