I'm trying to send an image to backend through form field in React. I'm first assigning the state to empty like this in my constructor class
this.state = {
image: "",
}
I'm then making a handleChange function for both image and normal text fields.
handleChange(event) {
const state = this.state;
switch (event.target.name) {
case 'image':
state.image = event.target.files[0];
break;
default:
state[event.target.name] = event.target.value;
}
this.setState(state);
}
In the handleSubmit function, i'm calling the FormData function and appending the image to it like this
handleSubmit(event) {
event.preventDefault();
const { syllabus,image } = this.state;
let formData = new FormData();
formData.append('image', image);
axios.post('api', { syllabus, formData })
.then((response) => {
console.log(response);
});
}
Finally, this is my form field
<span className="btn btn-default btn-file file-choose">
<input type="file" name="image" placeholder="Enter Image" onChange={this.handleChange} />
</span>
When i'm submitting this form and checking my 'Network' tab in Chrome console, the formData seems to be empty, i.e. no image is passed. When i call the backend route with a file selected, the file is uploaded, but i cant achieve this from React frontend and image never gets passed. Where am i going wrong?