Mad*_*Air 6 javascript html5 json blob web-storage
我正在尝试将blob通过AJAX检索的数据(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);
Run Code Online (Sandbox Code Playgroud)
代码在此处进行了改编,只需稍作修改即可使用localStorage.localStorage将所有数据保存为字符串,因此blob需要在保存之前以某种方式进行字符串化.
JSON 不会将blob作为其支持类型之一处理,因此这段代码失败并不奇怪.
有没有办法让blob进入localStorage?
只需将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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7792 次 |
| 最近记录: |