简体   繁体   中英

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

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.

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/

This is a debatable matter, but there are some lines we can draw here, I am quoting MDN here:

The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

so between file and blob, it's a matter of needed functionality (my preference is blob as it's a bit more handy).

now between blob and ArrayBuffer, this one is tricky, since it totally depends on what you need, ArrayBuffer is very helpful in some cases but it's a structured and it's a

fixed-length container for binary data

so your file size can make a huge difference.

another big point is, ArrayBuffer is in-memory, while blob can be any where, disk or memory, so with using blob you might be reducing over head a lot. so for your case, imho, blob wins.

now on a side note, I don't know what you are trying to do exactly, but storing the whole file in a db is not a good idea unless your target is indexing the whole file content and querying it, because, not all user devices can handle that type of overload, so, if you don't need the content, index the file names only, it saves time and storage space.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM