应用HTML5 IndexDB储存图象和文档的示例

日期:2020-10-13 类型:科技新闻 

关键词:在线网页制作,建网页,个人简介网页制作,简单网页,建立网页

有1天,大家写了有关怎样在localStorage中储存图象和文档的文章内容,它是有关大家今日能用的好用现实主义。 但是,localStorage有1些特性危害 - 大家将在稍后的blog中探讨这个难题 - 而且将来期待的方式是应用IndexedDB。 在这里,我将向您详细介绍怎样在IndexedDB中储存图象和文档,随后根据ObjectURL展现它们。

本文是汉语翻译过来的,原文在这里 Storing images and files in IndexedDB

有关作者: Robert Nyman [Editor emeritus]

Technical Evangelist & Editor of Mozilla Hacks. Gives talks & blogs about HTML5, JavaScript & the Open Web. Robert is a strong believer in HTML5 and the Open Web and has been working since 1999 with Front End development for the web - in Sweden and in New York City. He regularly also blogs atrobertnyman.com and loves to travel and meet people.

应用IndexDB储存图象和文档的基本流程

最先,大家来谈谈大家将建立1个IndexedDB数据信息库,将文档储存到在其中随后将其读取并显示信息在网页页面中的流程:

1、建立或开启数据信息库
2、建立1个objectStore
3、将图象文档查找为blob
4、原始化1个数据信息库事情
5、储存图象blob到数据信息库中去
6、读取储存的文档并从中建立ObjectURL并将其设定为网页页面中图象元素的src

1、建立或开启数据信息库。

// IndexedDB
window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB,
    IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.OIDBTransaction || window.msIDBTransaction,
    dbVersion = 1;

/* 
    Note: The recommended way to do this is assigning it to window.indexedDB,
    to avoid potential issues in the global scope when web browsers start 
    removing prefixes in their implementations.
    You can assign it to a varible, like var indexedDB… but then you have 
    to make sure that the code is contained within a function.
*/

// Create/open database
var request = indexedDB.open("elephantFiles", dbVersion);

request.onsuccess = function (event) {
    console.log("Success creating/accessing IndexedDB database");
    db = request.result;

    db.onerror = function (event) {
        console.log("Error creating/accessing IndexedDB database");
    };
    
    // Interim solution for Google Chrome to create an objectStore. Will be deprecated
    if (db.setVersion) {
        if (db.version != dbVersion) {
            var setVersion = db.setVersion(dbVersion);
            setVersion.onsuccess = function () {
                createObjectStore(db);
                getImageFile();
            };
        }
        else {
            getImageFile();
        }
    }
    else {
        getImageFile();
    }
}

// For future use. Currently only in latest Firefox versions
request.onupgradeneeded = function (event) {
    createObjectStore(event.target.result);
};

应用它的预期方式是在建立数据信息库时开启onupgradeneeded恶性事件或获得更高版本号号。 现阶段仅在Firefox中适用此作用,但很快将在别的Web访问器中适用。 假如Web访问器不适用此恶性事件,则可使用已弃用的setVersion方式并联接到其onsuccess恶性事件。

2、建立1个objectStore(假如它尚不存在)

// Create an objectStore
console.log("Creating objectStore")
dataBase.createObjectStore("elephants");

在这里,您建立1个ObjectStore,您将储存数据信息 - 或在大家的事例中,文档 - 而且1旦建立,您不必须再次建立它,只需升级其內容便可。

3、将图象文档查找为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获得。现阶段只适用Firefox。 收到全部文档后,将blob推送到涵数以将其储存在数据信息库中。

4、原始化1个数据信息库事情

// Open a transaction to the database
var transaction = db.transaction(["elephants"], IDBTransaction.READ_WRITE);

要刚开始向数据信息库写入內容,您必须应用objectStore名字和要实行的实际操作种类(在本例中为read和write)起动事务管理。

5、储存图象blob到数据信息库中去

// Put the blob into the dabase
transaction.objectStore("elephants").put(blob, "image");

1旦事务管理到位,您将得到对所需objectStore的引入,随后将您的blob放入在其中并为其出示密匙。

6、读取储存的文档并从中建立ObjectURL并将其设定为网页页面中图象元素的src

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

应用同样的事务管理来获得不久储存的图象文档,随后建立1个objectURL并将其设定为网页页面中图象的src。 比如,这还可以是1个额外到脚本制作元素的JavaScript文档,随后它将分析JavaScript。

最终详细编码

(function () {
    // IndexedDB
    var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB,
        IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.OIDBTransaction || window.msIDBTransaction,
        dbVersion = 1.0;

    // Create/open database
    var request = indexedDB.open("elephantFiles", dbVersion),
        db,
        createObjectStore = function (dataBase) {
            // Create an objectStore
            console.log("Creating objectStore")
            dataBase.createObjectStore("elephants");
        },

        getImageFile = function () {
            // 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");
                    
                    // Blob as response
                    blob = xhr.response;
                    console.log("Blob:" + blob);

                    // Put the received blob into IndexedDB
                    putElephantInDb(blob);
                }
            }, false);
            // Send XHR
            xhr.send();
        },

        putElephantInDb = function (blob) {
            console.log("Putting elephants in IndexedDB");

            // Open a transaction to the database
            var transaction = db.transaction(["elephants"], IDBTransaction.READ_WRITE);

            // Put the blob into the dabase
            var put = transaction.objectStore("elephants").put(blob, "image");

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

    request.onerror = function (event) {
        console.log("Error creating/accessing IndexedDB database");
    };

    request.onsuccess = function (event) {
        console.log("Success creating/accessing IndexedDB database");
        db = request.result;

        db.onerror = function (event) {
            console.log("Error creating/accessing IndexedDB database");
        };
        
        // Interim solution for Google Chrome to create an objectStore. Will be deprecated
        if (db.setVersion) {
            if (db.version != dbVersion) {
                var setVersion = db.setVersion(dbVersion);
                setVersion.onsuccess = function () {
                    createObjectStore(db);
                    getImageFile();
                };
            }
            else {
                getImageFile();
            }
        }
        else {
            getImageFile();
        }
    }
    
    // For future use. Currently only in latest Firefox versions
    request.onupgradeneeded = function (event) {
        createObjectStore(event.target.result);
    };
})();

访问器适用

URL API适用性

indexDb

Github源代码

以上便是本文的所有內容,期待对大伙儿的学习培训有一定的协助,也期待大伙儿多多适用脚本制作之家。