I'm currently trying to make the user can edit their profile picture, I'm using nodejs, react & multer for that. On the other hand I receive an error when I send my form, I show you my code I hope you can help me.
Sending the form gives me no error when I put a req.body.file in my edit function but then the image of my profile is undefined, I also tried req.file[0].filename, which doesn't work either.
I would like that when the user uploads an image it is downloaded in my images folder and that it is also displayed on the user's profile
I thank you in advance
CodePudding user response:
I didn't see your implementation for React updateUser
, but looks like you are using the key avatar
when uploading a file but accessing it via image
key.
Try to change your router to
router.put('/update/:id', requiresAuth, upload.single('avatar'), updateUser)
and make sure you submit the form with Content-Type header multipart/form-data
CodePudding user response:
when doing a put request you are sending your data in JSON not in form data. you need to do something like this
const onSubmit = () => {
const formData = new FormData();
formData.append("firstName", firstName);
....
formData.append("avatar", avatar);
also FileReader.readAsDataURL return string but multer needs value of type File, so we need to directly store event.target.files[0] inside state so that multer can read it.
make sure you have express middleware
app.use(express.json());
not but the least upload.single("avatar")
it should be the name of variable
hope these changes help you.