Dark Knight
Dark Knight

Reputation: 1083

Formdata is blank at the backend

I pass image data by appending with formdata in reactjs

This is the handler for this

handleUserImage(e) {
    const input = e.target
    if (input.files && input.files[0]) {
      const reader = new FileReader()
      reader.onload = (r) => {
        const formdata = new FormData()
        formdata.append('photos', input.files[0])
        formdata.append('fileName', input.files[0].name)
        this.props.uploadImage({ image: formdata })
      }
      reader.readAsDataURL(input.files[0])
    }
  }

and when I console it to backend it looks like blank object

{ image: {} } 

Then how can I pass formdata and upload the image

Edit : Upload image api call

export const uploadImage = (data) => {
  console.log(data)
  return fetch(`http://hostName:3001/town/image`, {
    method: 'POST',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    body: data
  })
  .then((res) => {
    return res.json()
  })
  .then((payload) => {
    console.log(payload)
    return payload
  }).catch((error) => {
   throw error
  })
}

Upvotes: 1

Views: 1727

Answers (2)

Endless
Endless

Reputation: 37786

Why use FileReader, upload it as base64 and append file name separately?

you can just do

handleUserImage (evt) {
  const file = evt.target.files[0]
  if (file) {
    const formdata = new FormData()
    formdata.append('photos', file)
    this.props.uploadImage({ image: formdata })
  }
}
  • You save a few bytes,
  • avoid unnecessary decode & encode calculations
  • runs faster
  • saves ~3x bandwidth

FormData.append(name, value, filename)

name
The name of the field whose data is contained in value.

value
The field's value. This can be a USVString or Blob (including subclasses such as File).

filename Optional
The filename reported to the server (a USVString), when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.

-- MDN - FormData.append()

Upvotes: 1

Quentin
Quentin

Reputation: 943128

when I console it to backend it looks like blank object

This is normal.

 headers: {
       'Content-Type': 'multipart/form-data'
 },

Multipart form data MIME types need to have a parameter to describe the boundary marker (so parsers know where one field ends and the next begins).

Yours is missing it. What's more, there is no way for you to know what it will be.

Don't override the Content-Type header, allow fetch to generate it from the FormData object. Remove the code I quoted entirely.

Upvotes: 1

Related Questions