i'm doing image upload in my mern app and i'm using express-fileupload
package, in the frontend i'm sending a image in FormData, but backend recives null.
frontend
const [infos, setInfos] = useState({title: '', text: '', image: ''})
const handleImg = (e) => {
const { files } = e.target
const formData = new FormData()
formData.append('image', files[0])
setInfos({ ...infos, image: formData.get('file') }) // image is null if i put formData itself
}
const submit = async(e) => {
e.preventDefault()
console.log(infos) // {title: 'titlw', text: 'text', image: File}
try{
await axios.post('/upload', infos, {headers: {'Content_Type': 'multipart/form-data'}})
}
catch(err) console.log(err)
}
<form onSubmit={submit} enctype='multipart/form-data' >
<input
type='file'
accept='image/*'
name='image'
onChange={handleImg}
/>
</form>
backend
import fileUpload from 'express-fileupload'
app.use(fileUpload())
app.post('/upload', (req, res) => {
console.log(req.files) // undefined
console.log(req.body) // {title: 'value', text: 'value', image: ''}
// if(req.files){
// const {image} = req.files
// image.mv(__dirname+'/client/uploads/'+image.name)
}
})
When i check infos
on the frontend, there is data, but when i requested to Express backend, all the text infos are there, but image is empty in the req.body
and req.files
is undefined. I spent alomst all yesterday on this, still can't solve.
maybe you send wrong const, you set "infos" but you send "info".