0

I'm trying to send data and upload an image to the backend (Node.js) in the same request, but when I try to upload the image, the other properties are found as undefined on the backend.

const Imgdata = new FormData()
Imgdata.append('file', this.state.choiceImgUrl)

  axios.post("http://localhost:8080/api/choices/img", Imgdata, { 
     headers: { 'Content-type': 'application/json' },
     data:{ 
        id:this.state.id,
        username:this.state.username
     }
  })
  .then(res => {
     if(res.data.success){
        this.setState({ successUpload:true })
     }
     else {
        alert('error in upload data')
        this.setState({ Uploadloading:false })

     }
  })

The id and username properties are undefined in the backend, and if I remove Imgdata, All data is transferred successfully, but without the file.

How can I upload the file along with some data to the backend?

Anuj Pancholi
  • 1,153
  • 8
  • 13

1 Answers1

0

sending data between frontend<->server can can take place in various formats - in this case I recommend [Form] (as the file is ultimately a binary code)

const formData = new FormData();
formData.append('key1', value1);
formData.append('key2', value2);

Also your header should include(instead application.json) -

Content-Type: multipart/form-data; boundary=something

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type

When you pack the whole structure into a variable - just pass it as a parameter to the function

randomService.uploadData(formData)

But also the backend should be constructed - to receive a specific value.

I'm shooting that server currently accepting application / json - so I looping You to another thread -

How to Allow Form-Data in NodeJS

Piotr Żak
  • 2,046
  • 5
  • 18
  • 30