11

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.

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Jesse Kinsman
  • 732
  • 2
  • 7
  • 20
  • Why? What are you trying to accomplish? – SLaks Mar 14 '13 at 00:48
  • You would normally encode a file with something like base64 first; serializing with JSON just puts something into a readily parsable data structure, but doesn't necessarily handle things like binary file content very well. – Jared Farrish Mar 14 '13 at 00:48
  • Trying to save to local storage so I can later read the file on page load. I don't want to save to base64, binary or text for that matter as if the file changes, I won't be able to load the changes. I will be stuck with what I had originally read into the FileReader at the time of the form submit. – Jesse Kinsman Mar 14 '13 at 16:17

1 Answers1

10

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.)

Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
  • 1
    I guess that is kind of what I was hoping for, but I was trying one last hope by asking the question. Thanks for confirming. It seems the browser could encrypt the file path and decrypt when you try and read it. – Jesse Kinsman Mar 15 '13 at 04:26