题意:JavaScript 将 Blob 保存到 localStorage

问题背景:

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

我正在尝试将通过 AJAX 获取的 Blob 数据(favicon)保存到 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.

这段代码是从这里修改而来的,做了一些小的修改以使其与 localStorage 配合使用。localStorage 会将所有数据保存为字符串,因此在保存之前,Blob 需要以某种方式被字符串化。

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

JSON 不处理 Blob 作为其支持的类型之一,因此这段代码失败并不奇怪。

Is there any way to get the blob into localStorage?

有没有办法将 Blob 存储到 localStorage 中?

问题解决:

Just store the blob as a data uri in local storage

只需将 Blob 作为数据 URI 存储在 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...
    //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);

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐