The other day we wrote about how to save images and files in localStorage, it was about the pragmatism available to us today. However, localStorage has some performance implications - we will discuss this in a later blog - and the desired approach in the future is to use IndexedDB. Here I'll show you how to store images and files in IndexedDB and then render them via ObjectURL.
This article is translated, the original text is here Storing images and files in IndexedDB
About the author: 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.
General steps for using IndexDB to store images and filesFirst, let's talk about the steps we will take to create an IndexedDB database, save the file into it and then read it out and display it in the page:
1. Create or open a database
2. Create an objectStore
3. Retrieve image files as blobs
4. Initialize a database transaction
5. Save the image blob to the database
6. Read out the saved file and create an ObjectURL from it and set it to the src of the image element in the page
1. Create or open a database. // IndexedDBwindow.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 databasevar 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 versionsrequest.onupgradeneeded = function (event) { createObjectStore(event.target.result);};The expected way to use it is to fire the onupgradeneeded event when creating the database or to get a higher version number. This feature is currently only supported in Firefox, but will be supported in other web browsers soon. If your web browser does not support this event, you can use the deprecated setVersion method and connect to its onsuccess event.
2. Create an objectStore (if it does not exist yet)// Create an objectStoreconsole.log(Creating objectStore)dataBase.createObjectStore(elephants);
Here, you create an ObjectStore where you will store data - or in our case, files - and once created, you don't need to recreate it, just update its content.
3. Retrieve image files as blobs // Create XHRvar xhr = new XMLHttpRequest(), blob;xhr.open(GET, elephant.png, true); // Set the responseType to blobxhr.responseType = blob; 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();This code directly gets the contents of the file as a blob. Currently only Firefox is supported. After receiving the entire file, send the blob to the function to store it in the database.
4. Initialize a database transaction// Open a transaction to the databasevar transaction = db.transaction([elephants], IDBTransaction.READ_WRITE);
To start writing to the database, you need to start a transaction with the objectStore name and the type of operation you want to perform (in this case, read and write).
5. Save the image blob to the database// Put the blob into the dabasetransaction.objectStore(elephants).put(blob, image);
Once the transaction is in place, you get a reference to the desired objectStore, then place your blob into it and give it the key.
6. Read out the saved file and create an ObjectURL from it and set it to the src of the image element in the page // 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 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);};Use the same transaction to get the image file you just stored, then create an objectURL and set it to the src of the image in the page. For example, this could also be a JavaScript file attached to a script element, which will then parse the JavaScript.
The final complete code (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); };})(); Browser supportURL API support
indexDb
Github source code
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.