Load Image/Video from IndexedDB

Viewed 111

I am working on a PWA project where I have created an IndexedDB and stored the images and videos in it. On the next reload of page, if image/video is available in IndexedDB, it should load it from there.

function fetchMedia(id) {
    var transaction = db.transaction(["media"]);
    var objectStore = transaction.objectStore("media");
    var request = objectStore.get(id);

    request.onerror = function(event) {
       console.log("Unable to retrieve daa from database!");
       return "";
    };

   request.onsuccess = function(event) {
       var imgFile = request.result;
       console.log(imgFile)
       var imgURL = window.URL.createObjectURL(imgFile);
       return imgURL;
   };
}

It always returns undefined. When I console.log the imgFile, it shows that it's there in the IndexedDB:

enter image description here

File in IndexedDB:

enter image description here

I have also tried this but no success yet:

var imgURL = window.URL.createObjectURL(new Blob(imgFile, {'type': 'application/octet-stream'}));

What's the correct approach to load the files from IndexedDB?

2 Answers

If your screenshot is accurate, then request.result is not an image, it's an object {id: '13388-7247-6247-62584', file: Blob, ...}. You didn't just store the image file, you wrapped it in an object. So what you're getting back out is an object.

Try imgFile = request.result.file; instead.

You cannot return inside the callback, you should wrap it in a promise.

Related