有一天,我們寫了關於如何在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 inweden and inweden and in New York City. He regularly also blogs atrobertnyman.com and loves to travel and meet people.
使用IndexDB儲存映像和檔案的常規步驟首先,我們來談談我們將創建一個IndexedDB資料庫,將文件保存到其中然後將其讀出並顯示在頁面中的步驟:
1、建立或開啟資料庫
2、創建一個objectStore
3.將影像檔案檢索為blob
4.初始化一個資料庫事物
5.保存影像blob到資料庫中去
6、讀出已儲存的檔案並從中建立ObjectURL並將其設定為頁面中圖像元素的src
1、建立或開啟資料庫。// IndexedDBwindow.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB, IDBTransaction = window.IDBTranssaction || window.msIndexedDB, 資料, dbVersion = 1;/* 註: 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 web browsers start removing prefixes in their implementations.al can indexedDB… but then you have to make sure that the code is contained within a function.*/// Create/open databasevar request = indexedDB.open(elephantFiles, dbVersion);request.onsuccess = function (event) { console.log(Success creating/accessing Indexed / ; 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 = var setVersion = var setVersion = var setVersion = var setVersion = var setVersion = db.setVersion(dbVersion); setVersion.onsuccess = function () { createObjectStore(db); getImageFile(); }; } else { getImageFile(); } } else { getImageFile(); }}// For future use. Currently only in latest Firefox versionsrequest.onupgraden event.target.result);};
使用它的預期方法是在建立資料庫時觸發onupgradeneeded事件或取得更高版本號。 目前僅在Firefox中支援此功能,但很快將在其他網頁瀏覽器中支援。 如果網路瀏覽器不支援此事件,則可以使用已棄用的setVersion方法並連接到其onsuccess事件。
2、創建一個objectStore(如果它尚不存在)// Create an objectStoreconsole.log(Creating objectStore)dataBase.createObjectStore(elephants);
在這裡,您創建一個ObjectStore,您將存儲數據- 或者在我們的例子中,文件- 並且一旦創建,您不需要重新創建它,只需更新其內容即可。
3.將影像檔案檢索為blob// Create XHRvar xhr = new XMLHttpRequest(), blob;xhr.open(GET, elephant.png, true);// Set the responseType to blobxhr.responseType = blob;xhr.addEventListener(load, function () { if (ifunction ( xhr.status === 200) { console.log(Image retrieved); // File as response blob = xhr.response; // Put the received blob into IndexedDB putElephantInDb(blob); }}, false);// Send XHRxhr.send();
此程式碼直接將檔案的內容當作blob獲取。目前只支援Firefox。 收到整個檔案後,將blob傳送到函數以將其儲存在資料庫中。
4.初始化一個資料庫事物// Open a transaction to the databasevar transaction = db.transaction([elephants], IDBTransaction.READ_WRITE);
若要開始寫入內容,您需要使用objectStore名稱和要執行的操作類型(在本例中為read和write)啟動交易。
5.保存影像blob到資料庫中去// Put the blob into the dabasetransaction.objectStore(elephants).put(blob, image);
一旦事務到位,您將獲得對所需objectStore的引用,然後將您的blob放入其中並為其提供金鑰。
6、讀出已儲存的檔案並從中建立ObjectURL並將其設定為頁面中圖像元素的src// Retrieve the file that was just storedtransaction.objectStore(elephants).get(image).onsuccess = function (event) { var imgFile = event.target.result; console.log(Got elephant! + imgFile); // Get 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); ;};
使用相同的事務來取得剛剛儲存的映像文件,然後建立一個objectURL並將其設定為頁面中映像的src。 例如,這也可以是一個附加到腳本元素的JavaScript文件,然後它將解析JavaScript。
最後完整程式碼。 || window.msIDBTransaction, dbVersion = 1.0; // Create/open database var request = indexedDB.open(elephantFiles, dbVersion), db, createObjectStore = function (dataBase) { // Create an objectStore console.Base(Cunction (dataBase) { // Create an objectStore console.Baselog; (elephants); }, getImageFile = function () { // Create XHR var xhr = new XMLHttpRequest(), blob; xhr.open(GET, elephant.png, true); // Set the responseType to blob xhr.responseType = blob; x 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 varmgFile); 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.revoking ObjectURL URL. ; 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 (State)s = function (State); 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原始碼
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。