0

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?

Barry Bonds
  • 118
  • 2
  • 11

3 Answers3

0

You need to send header for content-type

const config = {
        headers: { 'content-type': 'multipart/form-data' }
    }

    return axios.post('api', { syllabus, formData }, config)
khawar jamil
  • 166
  • 4
0

In your HTML, you should have

<form enctype="multipart/form-data">
   ...rest of your code
</form>

And if you want to inspect data, try logging using

for (let obj of formData.entries()) {
   console.log(`${obj[0]} => ${obj[1]}`); 
}
Prakash Kandel
  • 1,043
  • 6
  • 12
0

I Worked it out myself. First i assigned a default state this.state={image: new File([''], ''),}

This is its handler function

handleIChange() { const inputFile = $("input#input-image")[0].files[0]; this.setState({ image: inputFile }); }

This is how it is getting submitted

handleSubmit(event) {
  event.preventDefault();
  const image = this.state.image;
  let formData = new FormData();
  formData.append("image", $("input#input-image")[0].files[0]);
  //console.log("image3", $("input#input-image")[0].files[0])
  //console.log("Data", formData)
  const config = {
    headers: {
      'Content-Type': 'multipart/form-data;boundary=${data._boundary}'
    }
  };
  axios.post('api', formData, config)
    .then((response) => {
      console.log(response);
      let id = response.data._id;
      this.props.history.push('route);
    });
}
Barry Bonds
  • 118
  • 2
  • 11