9

我正在尝试将blob通过 AJAX 检索到的数据(网站图标)保存到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);

代码从此处改编,稍作修改以使其与localStorage. localStorage 将所有数据保存为字符串,因此在保存之前需要以某种方式对 blob 进行字符串化。

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

有什么方法可以将 blob 放入 localStorage?

4

1 回答 1

12

只需将 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);
于 2014-01-09T01:07:20.700 回答