You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Step 2: Set Up the Schema for image property, an example of uploading a user profile image.
image: {type: Object}
If multiple images
images: {type: Array}
Step 3: Set up middleware file multer.js in the middlewares folder
constmulter=require('multer')conststorage=multer.diskStorage({destination:function(req,file,cb){cb(null,'uploads/')},filename:function(req,file,cb){cb(req.file,file.originalname.split(' ').join('-'))// file name change split with space and join with ‘-’}})constupload=multer({storage:storage})module.exports={
upload
}
Step 4: In the routes.js file add the middleware upload function by importing multer middleware
const{ upload }=require("../app/middlewares/multer")router.post('/users/register',upload.single('image'),usersController.register)// If multiple images you can use upload.array('images',10) // field name images and 10 is number of images you can upload
Step 5: In user controller handle files.
usersController.register=(req,res)=>{constbody=req.bodyconstuser=newUser(body)user.image=req.file// if multiple images upload.array('images',10), req.files// user.images = req.filesuser.save().then((user)=>{res.json(user)}).catch((err)=>{res.json(err)})}
Step 6: Create the uploads folder outside the react folder and make it available by adding this line.