濮阳杆衣贸易有限公司

主頁(yè) > 知識(shí)庫(kù) > 使用HTML5 IndexDB存儲(chǔ)圖像和文件的示例

使用HTML5 IndexDB存儲(chǔ)圖像和文件的示例

熱門標(biāo)簽:威海營(yíng)銷外呼系統(tǒng)招商 濟(jì)南辦理400電話 鄭州電銷外呼系統(tǒng)違法嗎 跟電銷機(jī)器人做同事 漳州人工外呼系統(tǒng)排名 中紳電銷智能機(jī)器人 ai電銷機(jī)器人連接網(wǎng)關(guān) 鶴壁手機(jī)自動(dòng)外呼系統(tǒng)怎么安裝 農(nóng)村住宅地圖標(biāo)注

有一天,我們寫了關(guān)于如何在localStorage中保存圖像和文件的文章,它是關(guān)于我們今天可用的實(shí)用主義。 然而,localStorage有一些性能影響 - 我們將在稍后的博客中討論這個(gè)問(wèn)題 - 并且未來(lái)期望的方法是使用IndexedDB。 在這里,我將向您介紹如何在IndexedDB中存儲(chǔ)圖像和文件,然后通過(guò)ObjectURL呈現(xiàn)它們。

本文是翻譯過(guò)來(lái)的,原文在這里 Storing images and files in IndexedDB

關(guān)于作者: 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存儲(chǔ)圖像和文件的常規(guī)步驟

首先,我們來(lái)談?wù)勎覀儗?chuàng)建一個(gè)IndexedDB數(shù)據(jù)庫(kù),將文件保存到其中然后將其讀出并顯示在頁(yè)面中的步驟:

1、創(chuàng)建或打開數(shù)據(jù)庫(kù)
2、創(chuàng)建一個(gè)objectStore
3、將圖像文件檢索為blob
4、初始化一個(gè)數(shù)據(jù)庫(kù)事物
5、保存圖像blob到數(shù)據(jù)庫(kù)中去
6、讀出保存的文件并從中創(chuàng)建ObjectURL并將其設(shè)置為頁(yè)面中圖像元素的src

1、創(chuàng)建或打開數(shù)據(jù)庫(kù)。

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

使用它的預(yù)期方法是在創(chuàng)建數(shù)據(jù)庫(kù)時(shí)觸發(fā)onupgradeneeded事件或獲取更高版本號(hào)。 目前僅在Firefox中支持此功能,但很快將在其他Web瀏覽器中支持。 如果Web瀏覽器不支持此事件,則可以使用已棄用的setVersion方法并連接到其onsuccess事件。

2、創(chuàng)建一個(gè)objectStore(如果它尚不存在)

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

在這里,您創(chuàng)建一個(gè)ObjectStore,您將存儲(chǔ)數(shù)據(jù) - 或者在我們的例子中,文件 - 并且一旦創(chuàng)建,您不需要重新創(chuàng)建它,只需更新其內(nèi)容即可。

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

此代碼直接將文件的內(nèi)容作為blob獲取。目前只支持Firefox。 收到整個(gè)文件后,將blob發(fā)送到函數(shù)以將其存儲(chǔ)在數(shù)據(jù)庫(kù)中。

4、初始化一個(gè)數(shù)據(jù)庫(kù)事物

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

要開始向數(shù)據(jù)庫(kù)寫入內(nèi)容,您需要使用objectStore名稱和要執(zhí)行的操作類型(在本例中為read和write)啟動(dòng)事務(wù)。

5、保存圖像blob到數(shù)據(jù)庫(kù)中去

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

一旦事務(wù)到位,您將獲得對(duì)所需objectStore的引用,然后將您的blob放入其中并為其提供密鑰。

6、讀出保存的文件并從中創(chuàng)建ObjectURL并將其設(shè)置為頁(yè)面中圖像元素的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);
};

使用相同的事務(wù)來(lái)獲取剛剛存儲(chǔ)的圖像文件,然后創(chuàng)建一個(gè)objectURL并將其設(shè)置為頁(yè)面中圖像的src。 例如,這也可以是一個(gè)附加到腳本元素的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源碼

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

標(biāo)簽:紅河 萍鄉(xiāng) 咸陽(yáng) 文山 甘南 惠州 蘇州 營(yíng)口

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《使用HTML5 IndexDB存儲(chǔ)圖像和文件的示例》,本文關(guān)鍵詞  使用,HTML5,IndexDB,存儲(chǔ),圖像,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《使用HTML5 IndexDB存儲(chǔ)圖像和文件的示例》相關(guān)的同類信息!
  • 本頁(yè)收集關(guān)于使用HTML5 IndexDB存儲(chǔ)圖像和文件的示例的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    浦江县| 新绛县| 无棣县| 曲周县| 仁布县| 乡城县| 称多县| 稷山县| 游戏| 奈曼旗| 博乐市| 宝应县| 屏边| 隆昌县| 青海省| 涞水县| 凭祥市| 杂多县| 江门市| 康定县| 金溪县| 南投县| 岳池县| 大名县| 牙克石市| 光山县| 临夏市| 射阳县| 枞阳县| 文水县| 东莞市| 灌南县| 祁阳县| 蒙山县| 屏边| 泰宁县| 彰化市| 班戈县| 江华| 即墨市| 定兴县|