How can I serialize an input File object to JSON?

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

    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:

    
    

提交回复
热议问题