How can I serialize an input File object to JSON?

后端 未结 6 1744
粉色の甜心
粉色の甜心 2021-01-14 04:12

I want to convert an HTML input file to a JSON string like this:

var jsonString = JSON.stringify(file);
console.log( file );
console.log( jsonString );
         


        
6条回答
  •  南方客
    南方客 (楼主)
    2021-01-14 04:54

    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 it
    var newObject  = {
       'lastModified'     : fileObject.lastModified,
       'lastModifiedDate' : fileObject.lastModifiedDate,
       'name'             : fileObject.name,
       'size'             : fileObject.size,
       'type'             : fileObject.type
    };  
     
    // then use JSON.stringify on new object
    JSON.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 object
    JSON.stringify(fileObject);
    

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

提交回复
热议问题