Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to save a File object in LocalStorage and then reload a File via FileReader when a user comes back to a page?

For example, say the user loads some very large images or media files in to your web app. When they return you want your app to show what they've previously loaded, but can't keep the actual file data in LocalStorage because the data is too large.

like image 812
Ronald Avatar asked May 28 '11 00:05

Ronald


1 Answers

This is NOT possible with localStorage. Data stored in localStorage needs to be one of the primitive types that can be serializable. This does not include the File object.

For example, this will not work as you'd expect:

var el = document.createElement('input');
el.type='file';
el.onchange = function(e) {
  localStorage.file = JSON.stringify(this.files[0]);
  // LATER ON...
  var reader = new FileReader();
  reader.onload = function(e) {
    var result = this.result; // never reaches here.
  };
  reader.readAsText(JSON.parse(localStorage.f));
};
document.body.appendChild(el);

The solution is to use a more powerful storage option like writing the file contents to the HTML5 Filesystem or stashing it in IndexedDB.

like image 126
ebidel Avatar answered Nov 15 '22 15:11

ebidel