How can I serialize an input File object to JSON?

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

    Instead of looping through, or rather extracting each key one after the other, i came up with this function and i've used it image input.

    const fileObject = e.target.files[0];
    

    important notice

    //dont use shorthand for of loop
    for (const [key, value] in Object.entries(x)) 
    it can't loop through a file object in JS 
    

    Use this code instead

    const imageObject = {};
    
    for (const key in fileObject) {
        const value = fileObject[key];
        const notFunction = typeof value !== "function";
        notFunction && (imageObject[key] = value);
    }
    
    console.log(imageObject) // => should give you a normal JS object now
    

提交回复
热议问题