0

I am trying to upload a file using reactjs. I am not getting the right log. Before uploading, I wanted to see the output. But not getting the result.

Here what I have tried

state = {
    selectedFile: null
}

fileChangedHandler = event => {
    this.setState({
        selectedFile: event.target.files[0]
    })
    console.log(this.state.selectedFile) 
}
uploadHandler = () => {
    const formData = new FormData()
    var fd = formData.append("data", this.state.selectedFile, this.state.selectedFile.name)
    console.log(fd)

}

render() {
    return (
        <div>
            <input type="file" onChange={this.fileChangedHandler} />
            <button onClick={this.uploadHandler}>Upload!</button>
        </div>
    );
}
TheTechGuy
  • 1,568
  • 4
  • 18
  • 45
  • Possible duplicate of [Why is setState in reactjs Async instead of Sync?](https://stackoverflow.com/questions/36085726/why-is-setstate-in-reactjs-async-instead-of-sync) – Agney Jun 01 '18 at 06:42

1 Answers1

1

Try this

// Create your FormData object
    var formData = new FormData();
    formData.append('key1', 'value1'); // Test data
    formData.append('key2', 'value2'); // Test data
    
    // Display the key/value pairs array
    for (var pair of formData.entries()) {
        console.log(pair); 
    }
Parag Soni
  • 713
  • 7
  • 14