JavaScript将blob保存到localStorage

 mobiledu2502887507 发布于 2023-02-05 07:36

我正在尝试将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);

代码在此处进行了改编,只需稍作修改即可使用localStorage.localStorage将所有数据保存为字符串,因此blob需要在保存之前以某种方式进行字符串化.

JSON 不会将blob作为其支持类型之一处理,因此这段代码失败并不奇怪.

有没有办法让blob进入localStorage?

1 个回答
  • 只需将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);
    

    2023-02-05 07:58 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有