I'm building a Nodejs application with a user profile update. All user information updates perfectly except for the image. I am not able to save the image neither locally nor in the database. Could someone help me solve this? This is my code For the controller
const {createUser, getUserPerUsername, searchUsersPerUsername, addUserIdToCurrentUserFollowing,
removeUserIdToCurrentUserFollowing, findUserPerId, updateUser, deleteUser} = require('../queries/users.queries')
const request = require('request')
const directoryUploads = require('../path').directoryUploads
const path = require('path')
const fs = require('fs')
const upload = require('../Middleware/upload')
exports.userUpdate = async (req, res, next ) => {
const userId = req.params.userId
const user = await findUserPerId(userId)
const body = req.body
try {
if(user) {
let picture = req.files['picture'] ? req.files['picture'][0].filename : null
console.log("Picture : " +picture)
const user = await findUserPerId(userId)
console.log("User Old : " + user)
if (userOld.picture) {
if (picture) {
const pathImagePreview = path.join(directoryUploads, 'uploads/') + user.picture
fs.exists(pathImagePreview, exists => {
if (exists)
fs.unlinkSync(pathImagePreview)
})
} else {
picture = user.picture
}
}
const userUptd = await updateUser(userId, {
firstname: body.firstname,
lastname: body.lastname,
"local.email": body.email,
phones: body.phones,
picture: body.picture
})
console.log("Image uploaded successfully !!")
req.flash('success', [`User ${userUptd.username} updated!`])
res.redirect('/users/profile')
} else {
throw new Error('Please make sure to fill in the fields correctly!')
}
} catch (error) {
console.log(error)
req.flash('errors', [error.message])
req.flash('body', body)
}
}
here picture refers to the name of the input type="file". The error returned is "Cannot read property 'picture ' of undefined". I think that it's probably linked to the file retrieving