How do I save and restore a File object in local storage

pinoyyid picture pinoyyid · Oct 1, 2013 · Viewed 63k times · Source

I have an HTML5/javscript app which uses

<input type="file" accept="image/*;capture=camera" onchange="gotPhoto(this)">

to capture a camera image. Because my app wants to be runnable offline, how do I save the File (https://developer.mozilla.org/en-US/docs/Web/API/File) object in local storage, such that it can be retrieved later for an ajax upload?

I'm grabbing the file object from the using ...

function gotPhoto(element) { 
     var file = element.files[0];
     //I want to save 'file' to local storage here :-(
}

I can Stringify the object and save it, but when I restore it, it is no longer recognised as a File object, and thus can't be used to grab the file content.

I have a feeling it can't be done, but am open to suggestions.

FWIW My workaround is to read the file contents at store time and save the full contents to local storage. This works, but quickly consumes local storage since each file is a 1MB plus photograph.

Answer

George Mavritsakis picture George Mavritsakis · Oct 5, 2013

You cannot serialize file API object.

Not that it helps with the specific problem, but ... Although I haven't used this, if you look here it seems that there are ways (althought not supported yet by most browsers) to store the offline image data to some files so as to restore them afterwards when the user is online (and not to use localstorage)