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.
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.
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.
More specifically, IndexedDB data is stored in the browser profile folder.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With