Mozilla

Storing images and files in IndexedDB

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:

  1. Create or open a database.
  2. Create an objectStore (if it doesn’t already exist)
  3. Retrieve an image file as a blob
  4. Initiate a database transaction
  5. Save that blob into the database
  6. 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.

30 comments

Comments are now closed.

  1. Florian wrote on February 24th, 2012 at 2:25 am:

    Hello,

    Are you sure your demo is working on Firefox because on my side, it throw me an exception : “The object could not be cloned. ?

    This exception is also thrown in IE 10.

    This exception is thrown when you try to store a “complexe” object into the database.

    I was wondering that because I have the same issue on an application i am working on, and the only workaround I found is to store images in indexedDB as base64 string.

    Florian

  2. Robert Nyman wrote on February 24th, 2012 at 2:47 am:

    Thanks for asking!
    Sorry, I should have been more clear about that: when it comes to storing files specifically, it works in Firefox 11 and later – please try Firefox Beta or Firefox Aurora and latest Google Chrome.

    I’ll update the blog post with that info.

    I hope that IE10 will support storing files before it is officially released.

  3. Andrea Giammarchi wrote on February 26th, 2012 at 1:54 pm:

    so now we talk Robert, good stuff!

    1. Robert Nyman wrote on February 26th, 2012 at 2:01 pm:

      Thank you. :-)

  4. Andrea Doimo wrote on February 28th, 2012 at 8:20 am:

    I see the elephant iwth Chrome (19.0.1049.3 dev-m)
    Does this means that the demo worked fine? In the “Web browser support” section you state that Chrome doesn’t support some of the features listed.

    1. Robert Nyman wrote on February 28th, 2012 at 8:51 am:

      Thanks for asking!
      There seems to be a case where Google Chrome intermediately stores the URL, which falsely gives the impression that it works (but without storing the actual file).

      I’ve changed the blog post and demo code to use responseType blob, that goes hand in hand with this, and you can see it in action in the updated demo.

      For more information on the Google Chrome status, please see the relevant bug.

  5. abral wrote on March 6th, 2012 at 3:46 pm:

    I’ve developed two demos that save files in an indexeddb for the december dev derby, eLibri and FileSystemDB.

    1. Robert Nyman wrote on March 7th, 2012 at 1:28 am:

      Thanks for the tip!

      1. Ruben wrote on August 24th, 2012 at 8:46 am:

        Hi Abral, I´ve seen your app eLibri, GREAT!, I´m trying to do something of the sort with a MS SQL server and in ASP, i´m getting it all right till the getting the Json file from the server and putting it into the IndexedDB database, could you explain how you do it and maybe give us a glance at the server file that delivers the Json file? (I know it is in PHP but it would help) Thank´s in advance.

  6. Odin Hørthe Omdal wrote on March 14th, 2012 at 7:24 am:

    IDBTransaction.READ_WRITE is now called “readwrite”.

    I can tell you a bit about Opera:
    IndexedDB: I don’t think it’ll hit 12, but we’re working on it.
    XHR2 blob (and arraybuffer) is coming in Opera 12.
    onupgradeneeded: Of course we’re implementing the newest spec.

    1. Robert Nyman wrote on March 14th, 2012 at 7:31 am:

      Thanks!
      I’ve updated the post with information on Opera.

  7. Víctor Quiroz wrote on April 24th, 2012 at 10:49 am:

    Great Post! it’s the first that actually works. The only thing I would like to know is how to insert multiple rows using a loop?

    1. Víctor Quiroz wrote on April 24th, 2012 at 10:59 am:

      nevermind, It worked perfectly like this:

      putElephantInDb = function (json) {
      console.log(“Putting elephants in IndexedDB”);

      // Open a transaction to the database

      $.each(json[0], function(i, w){
      var transaction = db.transaction(["elephant"], IDBTransaction.READ_WRITE);

      // Put the blob into the dabase
      var put = transaction.objectStore(“elephant”).put(w, “json”);

      // Retrieve the file that was just stored
      transaction.objectStore(“elephant”).get(w.id, “json”).onsuccess = function (event) {
      var mijson = event.target.result;
      console.log(mijson);
      };
      });
      };

      1. Robert Nyman wrote on April 24th, 2012 at 3:05 pm:

        And glad you found a solution!

    2. Robert Nyman wrote on April 24th, 2012 at 3:02 pm:

      Thanks, glad you liked it!

  8. Anonymous wrote on May 20th, 2012 at 2:40 pm:

    Is there a way to download huge content (~1 GB in total) to a database where the database needs to be in a consistent state all the time (e.g. a graph)?
    - Parsing the whole blob is impossible due to its size.
    - Using a single transaction for all chunks isn’t possible either, since during the download we need to get back to the event loop, and therefore the transaction becomes inactive.
    - Using temporary object stores in the *same* database would be possible, but doubles the space needed during download.

    1. Robert Nyman wrote on May 22nd, 2012 at 2:13 am:

      Good question! At this time, I’m not aware of doing it in any optimal way with IndexedDB. Like you say, temporary object stores might work but it’s not the desired solution.

      If you come up with something clever, please let us know!

  9. Mitchell wrote on July 20th, 2012 at 12:51 am:

    Hello Robert,
    Thank you for demo.

    Do you know why I get a security error if I load an image from my Web server?

    Security Error: Content at http://wheredidmybraingo.com/image.html may not load data from blob:ebac76f2-366c-c34d-af7c-fb1312f82999.

    Thank you, Mitchell

  10. Mitchell wrote on July 20th, 2012 at 2:41 am:

    I fixed it :)

    I removed revokeObjectURL.

    Wish it was in documentation :(

    http://www.w3.org/TR/IndexedDB/

    Thank you again for demo, Mitchell

    1. Robert Nyman wrote on July 31st, 2012 at 9:15 am:

      Interesting. Why would revokeObjectURL throw that error for you?

  11. Sam wrote on August 27th, 2012 at 11:27 pm:

    How much data can be stored on client side using indexedDB? 5MB, 50MB or there is no limit?

    1. Robert Nyman wrote on August 28th, 2012 at 1:49 am:

      It is dependent on the web browser, but generally at least 50 MB.

      For Firefox, it’s 50 MB by default, and you can ask for more. More information in What is the storage limitation for “indexDB” in Firefox?

  12. Ruben wrote on September 25th, 2012 at 3:37 am:

    Hi Robert,
    Thanks for sharing this example, I´m trying to get this to work but instead of a image I´m trying to retrieve a Json file from a web service and putting it to the IndexedDB objectStore.
    It looks something like this: [{"field1":"value1"},{"field2":"value2"},{"field3":"value3"},{"field4":"value4"}]
    but as I’m a newbie to JavaScript it’s beeing a nightmare…
    do you think you can post a example in how to do it?
    Thanks in advance.
    Ruben.

    1. Robert Nyman wrote on September 25th, 2012 at 7:39 am:

      Can’t go into detail here, but if you have received JSON from the server, you can use the native JSON support in web browsers and then use the put method in the code above to save that into IndexedDB.

      1. Ruben wrote on September 25th, 2012 at 12:10 pm:

        Hi! thanks Robert, I’ve managed to do it, I’m only having a problem putting the records to the objectStore, I’m doing this:

        var result = eval( ‘(‘ + xhr.responseText + ‘)’ );
        for(i=0; i<result.length; i++){
        var transaction = db.transaction(["elephants"], IDBTransaction.READ_WRITE);
        var put = transaction.objectStore("elephants").put(result[i], "image");

        but it's actually putting something like this: [object Object],[object Object],[object Object],[object Object]" to the objectStore…
        I'm not sure if I have to use the eval() or even the loop, can you give me a hand please?

        1. Robert Nyman wrote on September 26th, 2012 at 2:00 am:

          Please don’t use eval, use native JSON as linked in my previous comment above.

          Then, in put the first value should be the value and the second shouldn’t be “image”, but rather the name of your key (unless you want to store it all in the same key).

          1. Ruben wrote on September 26th, 2012 at 11:45 am:

            I´ve just figured it out, I already have an object and dont need to do anything with it, just loop threw and put it to the objectStore.
            Thanks again Robert, and nice job on this code.
            Cheers.

          2. Robert Nyman wrote on September 26th, 2012 at 12:50 pm:

            Great! Good luck and thanks!

  13. Tom wrote on March 17th, 2013 at 2:19 pm:

    This works great for me in FF(19.02), but not in Chrome (25.0.1364.172 m) or IE (10.09.200…). The image src in the sample is pre set to “elephant.png”, so it gives the false impression that it works in those browsers as well, but I am getting an error: Uncaught Error: “DataCloneError: DOM IDBDatabase Exception 25″ on this line: var put = transaction.objectStore(“elephants”).put(blob, “image”);

    Is it because blobs are not supported in those browsers?

    Thanks
    Tom

    1. Robert Nyman [Editor] wrote on March 18th, 2013 at 2:53 am:

      Yes, I believe it could down to the blob support as responseType. The src of the img element should change to a blob reference, though, but I see what you mean.

Comments are closed for this article.