Sourabh Kumar Sourabh Kumar - 4 months ago 66
Node.js Question

how to send image name in database using multer and express

I'm trying to upload a photo with multer and express everything is ok. But i am not able to send the image name in mongoose database, the image are uploaded successfully in upload directory i got the imageUrl in body but i am not able to update the image name in mongoose database but the other details update successful check the below image when i print the body on console.
enter image description here



//file upload using multer
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
if (!file.originalname.match(/\.(jpg|png|JPEG)$/)) {
var err = new Error();
err.code = 'filetype';
return callback(err);
} else {
callback(null, Date.now() + file.originalname);
}

}
});
var upload = multer({
storage: storage,
limits: {
fileSize: 1000000
}
}).single('userImage');
app.patch('/updateProfile', authenticate, (req, res) => {
upload(req, res, function(err) {
var body = _.pick(req.body, ['name', 'email', 'mobile', 'imageUrl']);

User.findOneAndUpdate({
_id: req.user._id
}, {
$set: body
}, {
new: true
}).then((user) => {
if (!req.file) {
return res.send({
success: false,
msg: 'No file selected'
})
}
if (!user) {
res.status(404).send({
success: false,
msg: 'user not found'
})
} else {
body.imageUrl = req.file.filename;
console.log(body)
res.send({
sucess: true,
msg: 'update sucessfully',
user
})
}
}).catch((err) => {
res.send({
success: false,
msg: 'something wrong',
error: err
});
});
if (err) {
if (err.code === 'LIMIT_FILE_SIZE') {
return res.send({
success: false,
msg: 'limit file size 1MB '
})
} else if (err.code === 'filetype') {
return res.send({
success: false,
msg: 'Must be valid file extension only jpg or png'
})
} else {
return res.send({
success: false,
msg: 'something went wrong'
})
}
}

});
});




Answer Source
    var storage = multer.diskStorage({

    destination: function (req, file, callback) {

        callback(null, './images/post');

    },

    filename: function (req, file, callback) {

        if (!file.originalname.match(/\.(jpg|png|JPEG)$/)) {

            var err = new Error();

            err.code = 'filetype';

            return callback(err);

        } else {

            callback(null, Date.now() + file.originalname);

        }


    }

});

var upload = multer({ storage: storage, limits: { fileSize: 1000000 } }).single('imageUrl');

router.post('/posts',authenticate, (req, res) => {

    upload(req, res, function (err) {

        if (err) {

            if (err.code === 'LIMIT_FILE_SIZE') {

                return res.send({ success: false, msg: 'limit file size 1MB ' })

            } else if (err.code === 'filetype') {

                return res.send({ success: false, msg: 'Must be valid file extension only jpg or png' })

            } else {

                return res.send({ success: false, msg: 'something went wrong' })

            }

        } else {

            if (!req.file) {

                return res.send({ success: false, msg: 'No file selected' })

            }

            var post = new Post({

                heading: req.body.heading,

                body: req.body.body,

                imageUrl: req.file.filename,

                creator:req.user.id,

            });

            post.save().then((result) => {

                res.send({ post: result, sucess: true, msg: 'Post created' });

            }).catch((err) => {

                res.send({ sucess: false, msg: 'post not created', error: err })

            });

        }

    });


});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download