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
})
}
when I console it to backend it looks like blank object
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.