ITeye博客

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

jean7155 · 2013-03-19 11:45 · HTML5 · IndexedDB · Web前端 · HTML5 · IndexedDB · Markdown

目标:

创建和大概数据库(省略) 创建对象存储(省略) 以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);
};

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。