`
jean7155
  • 浏览: 61438 次
  • 性别: Icon_minigender_2
  • 来自: 上海
社区版块
存档分类
最新评论

IndexedDB学习三:保存图片和文件

阅读更多
目标:
  • 创建和大概数据库(省略)
  • 创建对象存储(省略)
  • 以BLOB形式获取图片文件
  • 启动数据库事务(省略)
  • 保存blob到数据库
  • 读取保存文件,创建ObjectURL在页面展示


以blob形式获取图片文件:
// Create XHR
var xhr = new XMLHttpRequest(),
    blob;
 
xhr.open("GET", "elephant.png", true);
// Set the responseType to blob
xhr.responseType = "blob";
 
xhr.addEventListener("load", function () {
    if (xhr.status === 200) {
        console.log("Image retrieved");
        
        // File as response
        blob = xhr.response;
 
        // Put the received blob into IndexedDB
        putElephantInDb(blob);
    }
}, false);
// Send XHR
xhr.send();

保存blob到数据库:
transaction.objectStore("elephants").put(blob, "image");

读取保存文件,创建ObjectURL在页面展示:
// Retrieve the file that was just stored
transaction.objectStore("elephants").get("image").onsuccess = function (event) {
    var imgFile = event.target.result;
    console.log("Got elephant!" + imgFile);
 
    // Get window.URL object
    var URL = window.URL || window.webkitURL;
 
    // Create and revoke ObjectURL
    var imgURL = URL.createObjectURL(imgFile);
 
    // Set img src to ObjectURL
    var imgElephant = document.getElementById("elephant");
    imgElephant.setAttribute("src", imgURL);
 
    // Revoking ObjectURL
    URL.revokeObjectURL(imgURL);
};

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics