Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexedDB: Store file as File or Blob or ArrayBuffer. What is the best option?

Tags:

Now most of browsers are supporting IndexedDB to store data/file directly as File, Blob or ArrayBuffer.

This code saves a IDB key 'File1' as File

<input type="file" id="userfile" /> var a = document.getElementById("userfile"); var b = a.files[0]; 

Now we can directly save this file to IDB using the following code

//LocalForage is a library for indexedDB developed by Mozilla //Note: localforage._config.driver=asyncStorage (IDB method) function run(){   //"File1" = IDB data table key and b=value   localforage.setItem("File1", b, function(err, value) {     console.log(err)   }); }  a.onchange = function(){   run() } 

This code saves a IDB key 'BlobFile' as Blob

mb = new Blob([b],{type:b.type});  function runB(){   localforage.setItem("BlobFile", mb, function(err, value){     console.log(err)   });     }  a.onchange = function(){   runB() } 

I want to know what is the best practice to store the file to IDB. (File/Blob/ArrayBuffer)

The files could be images or very small size videos.

like image 403
Ankit_Shah55 Avatar asked Aug 04 '15 07:08

Ankit_Shah55


People also ask

Can IndexedDB store files?

Not everything can be stored in IndexedDB on all platforms # If you are storing large, user-generated files such as images or videos, then you may try to store them as File or Blob objects. This will work on some platforms but fail on others. Safari on iOS, in particular, cannot store Blob s in IndexedDB.

What is IndexedDB blob?

IndexedDB provides large scale key-value type persistent storage that is available on most of modern browsers (Safari apparently will land support in iOS8 and Mac OS X 10.10). Check out its implementation status. Blob is a file-like binary object modern JavaScript engines can handle. File objects inherits from Blob.

Where is IndexedDB data stored?

More specifically, IndexedDB data is stored in the browser profile folder.


1 Answers

I recommend using Blob for images & videos as the API is fairly straightforward for downloading as blob and saving to db, as well as retrieving from db and creating URL for src attribute

Check this sample here for implementation https://hacks.mozilla.org/2012/02/storing-images-and-files-in-indexeddb/

like image 171
gafi Avatar answered Sep 28 '22 02:09

gafi