LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發文檔 其他文檔  
 
網站管理員

使用HTML5 IndexDB存儲圖像和文件

freeflydom
2024年10月7日 9:31 本文熱度 566

使用IndexedDB存儲圖像和文件


有一天,我們寫了關于如何在localStorage中保存圖像和文件的文章,它是關于我們今天可用的實用主義。 然而,localStorage有一些性能影響 - 我們將在稍后的博客中討論這個問題 - 并且未來期望的方法是使用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 at robertnyman.com and loves to travel and meet people.


使用IndexedDB存儲圖像和文件的常規步驟


首先,我們來談談我們將創建一個IndexedDB數據庫,將文件保存到其中然后將其讀出并顯示在頁面中的步驟:

1、創建或打開數據庫

2、創建一個objectStore

3、將圖像文件檢索為blob

4、初始化一個數據庫事物

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、創建一個objectStore(如果它尚不存在)

// Create an objectStore

console.log("Creating objectStore")

dataBase.createObjectStore("elephants");

在這里,您創建一個ObjectStore,您將存儲數據 - 或者在我們的例子中,文件 - 并且一旦創建,您不需要重新創建它,只需更新其內容即可。


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、初始化一個數據庫事物

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

一旦事務到位,您將獲得對所需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);

};

使用相同的事務來獲取剛剛存儲的圖像文件,然后創建一個objectURL并將其設置為頁面中圖像的src。 例如,這也可以是一個附加到腳本元素的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源碼


作者:一兵
鏈接:https://juejin.cn/post/6844903703921557518
來源:稀土掘金
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。



該文章在 2024/10/9 11:03:36 編輯過
關鍵字查詢
相關文章
正在查詢...
點晴ERP是一款針對中小制造業的專業生產管理軟件系統,系統成熟度和易用性得到了國內大量中小企業的青睞。
點晴PMS碼頭管理系統主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業務管理,結合碼頭的業務特點,圍繞調度、堆場作業而開發的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業的高效ERP管理信息系統。
點晴WMS倉儲管理系統提供了貨物產品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產管理,WMS管理系統,標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協同辦公管理系統。
Copyright 2010-2025 ClickSun All Rights Reserved

黄频国产免费高清视频,久久不卡精品中文字幕一区,激情五月天AV电影在线观看,欧美国产韩国日本一区二区
亚洲国产日韩欧美在线播放 | 色偷偷精品免费视频 | 亚洲中文字幕精品久久久久久直播 | 亚洲乱码国产精品 | 中文字幕精品三区视频 | 在线能看三级网站 |