How can I serialize an input File object to JSON? How can I serialize an input File object to JSON? json json

How can I serialize an input File object to JSON?


It is not possible to directly convert a File object into JSON using JSON.stringify in Chrome, Firefox and Safari.

You can make a work around to convert File object to string using JSON.stringify

Ex:

// get File Object  var fileObject = getFile();// reCreate new Object and set File Data into itvar newObject  = {   'lastModified'     : fileObject.lastModified,   'lastModifiedDate' : fileObject.lastModifiedDate,   'name'             : fileObject.name,   'size'             : fileObject.size,   'type'             : fileObject.type};   // then use JSON.stringify on new objectJSON.stringify(newObject);

You can also add the toJSON() behavior to your File object

EX:

// get File Object  var fileObject = getFile();// implement toJSON() behavior  fileObject.toJSON = function() { return {   'lastModified'     : myFile.lastModified,   'lastModifiedDate' : myFile.lastModifiedDate,   'name'             : myFile.name,   'size'             : myFile.size,   'type'             : myFile.type };}   // then use JSON.stringify on File objectJSON.stringify(fileObject);

Note: send a File Object to server using the POST HTTP method.


You have to read the file content using the FileReader API. The File object does not contain the file content (it is just a pointer toward the file, which allows you to read it later).

You can check out this HTML5Rocks article to find out more about the usage of this API.

var file = getAFile( );var success = function ( content ) {  console.log( JSON.stringify( content ) ); }var fileReader = new FileReader( );fileReader.onload = function ( evt ) { success( evt.target.result ) };fileReader.readAsText( file );


In case anyone is still looking for a solution to this please see my answer on a different post and working example on JSFiddle.

JS:

function getFiles(){    var files = document.getElementById("myFiles").files;    var myArray = [];    var file = {};    console.log(files); // see the FileList    // manually create a new file obj for each File in the FileList    for(var i = 0; i < files.length; i++){      file = {          'lastMod'    : files[i].lastModified,          'lastModDate': files[i].lastModifiedDate,          'name'       : files[i].name,          'size'       : files[i].size,          'type'       : files[i].type,      }       //add the file obj to your array      myArray.push(file)    }    //stringify array    console.log(JSON.stringify(myArray));}

HTML:

<input id="myFiles" type="file" multiple onchange="getFiles()" />