How can I serialize an input File object to JSON?

后端 未结 6 1714
粉色の甜心
粉色の甜心 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

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

提交回复
热议问题