有一天,咱們寫了關於如何在localStorage中保存圖像和文件的文章,它是關於咱們今天可用的實用主義。 然而,localStorage有一些性能影響 - 咱們將在稍後的博客中討論這個問題 - 而且將來指望的方法是使用IndexedDB。 在這裏,我將向您介紹如何在IndexedDB中存儲圖像和文件,而後經過ObjectURL呈現它們。html
本文是翻譯過來的,原文在這裏Storing images and files in IndexedDBhtml5
關於做者: Robert Nyman [Editor emeritus]git
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.github
首先,咱們來談談咱們將建立一個IndexedDB數據庫,將文件保存到其中而後將其讀出並顯示在頁面中的步驟:web
// 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事件。數據庫
// Create an objectStore
console.log("Creating objectStore")
dataBase.createObjectStore("elephants");
複製代碼
在這裏,您建立一個ObjectStore,您將存儲數據 - 或者在咱們的例子中,文件 - 而且一旦建立,您不須要從新建立它,只需更新其內容便可。瀏覽器
// 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發送到函數以將其存儲在數據庫中。bash
// Open a transaction to the database
var transaction = db.transaction(["elephants"], IDBTransaction.READ_WRITE);
複製代碼
要開始向數據庫寫入內容,您須要使用objectStore名稱和要執行的操做類型(在本例中爲read和write)啓動事務。函數
// Put the blob into the dabase
transaction.objectStore("elephants").put(blob, "image");
複製代碼
一旦事務到位,您將得到對所需objectStore的引用,而後將您的blob放入其中併爲其提供密鑰。性能
// 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);
};
})();
複製代碼