Search code examples
javascripthtmlfileapi

Javascript can you serialize a File object


I need to serialize a File object from a file input, so that the object can be saved, parsed back to a file object, and then read using the FileReader object.

Does anyone know if this is possible in Google Chrome?

I think the problem lies in the protection of the file.path property. Webkit browsers hide this property, so I am guessing when you serialize it, the path is removed.

Then of course, the FileReader is unable to read it without path information.

Here is an example:

var files = uploadControl.files[0];
var dataFile = JSON.stringify(files);
var newFile = JSON.parse(dataFile);
var reader = new FileReader();
reader.onload = (function(event) {
    var fileContents = event.target.result;
});
reader.readAsText(newFile);

Nothing happens. The reader is not loaded. If I pass the JSON object, it doesn't work either.


Solution

  • As a matter of principle, what you are asking for will not be possible. If it were possible to have some text which represented the file object, then you could construct that text from scratch, unserialize it, and thus get access to files the user did not grant permission to.

    (The exception to this is if the representative text is some sort of robustly-secret bitstring (cryptographically signed, or a sparse key in a lookup table) that only the browser could have given out in the first place — but I expect if that feature existed, it would be documented and you would have found it already.)