The other day we wrote about how to Save images and files in localStorage, and it was about being pragmatic with what we have available today. There are, however, a number of performance implications with localStorage – something that we will cover on this blog later – and the desired future approach is utilizing IndexedDB. Here I’ll walk you through how to store images and files in IndexedDB and then present them through an ObjectURL.
The general approach
First, let’s talk about the steps we will go through to create an IndexedDB data base, save the file into it and then read it out and present in the page:
- Create or open a database.
- Create an objectStore (if it doesn’t already exist)
- Retrieve an image file as a blob
- Initiate a database transaction
- Save that blob into the database
- Read out that saved file and create an ObjectURL from it and set it as the src of an image element in the page
Creating the code
Let’s break down all parts of the code that we need to do this:
Create or open a database.
// 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); | |
}; |
30 comments