Accessing FormData Values

后端 未结 11 849
误落风尘
误落风尘 2020-12-08 07:48

I have a FormData object which I create in javascript from an HTML form like so. The FormData object doesn\'t seem very well documente

11条回答
  •  没有蜡笔的小新
    2020-12-08 08:17

    If what you're trying to do is get the content of the FormData or append to it, this is what you should use:

    Let's say you want to upload an image like so:

     
    uploadPic(e)} />
    

    On change handler function:

    const handleChange = e => {
        // Create a test FormData object since that's what is needed to save image in server
    
       let formData = new FormData();
    
        //adds data to the form object
    
        formData.append('imageName', new Date.now());
        formData.append('imageData', e.target.files[0]);
    
    }
    

    append: adds an entry to the creates formData object where imageData is the key and e.target.files[0] is the property

    You can now send this imageData object which contains data of the image to your server for processing

    but to confirm if this formData has values a simple console.log(formData)/won't do it, what you should do is this:

    //don't forget to add this code to your on change handler 
    function
    for (var value of formData.values()) {
       console.log(value); 
    }
    

    //I hope that explains my answer, it works for vanilla JavaScript and React.js...thanks in advance for your upvote

提交回复
热议问题