JavaScript将blob保存到localStorage [英] JavaScript save blob to localStorage

查看:736
本文介绍了JavaScript将blob保存到localStorage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to save blob data (favicon) retrieved via AJAX, to 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需要以某种方式字符串化才能保存。

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 不会将blob作为其支持类型之一处理,因此这段代码失败并不奇怪。

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

有没有办法得到blob到localStorage?

Is there any way to get the blob into localStorage?

推荐答案

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

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

这篇关于JavaScript将blob保存到localStorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆