Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 730
Jesse Kinsman Avatar asked Mar 14 '13 00:03

Jesse Kinsman


People also ask

Can you serialize any object?

To serialize an object means to convert its state to a byte stream so way that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface, java.

Are JavaScript objects Serializable?

The process whereby an object or data structure is translated into a format suitable for transfer over a network, or storage (e.g. in an array buffer or file format). In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON. stringify() .


1 Answers

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

like image 83
Kevin Reid Avatar answered Oct 07 '22 06:10

Kevin Reid