Upload image then update with Multer and Express.js Upload image then update with Multer and Express.js mongoose mongoose

Upload image then update with Multer and Express.js


From the documentation of multer.single(fieldname)

Accept a single file with the name fieldname. The single file will be stored in req.file.


Because you are doing upload.single('image') your multer will accept file with the name image and store it to req.file.image. You are however referring it with filename. You should therefore replace req.file.filename with req.file.image.

Also when uploading a new file or editing you would want to check if the file exists before processing it with multer to avoid property of undefined error.

if (req.file) {  // your code}


You simply need to check if there is a file attached to the request using if (req.file) and modify the database query accordingly.So your post edit code can go like this:

router.put('/post/edit/:id', authenticate, upload.single('image'), (req, res) => {    const id = req.params.id;    const body = req.body;    console.log('body:', body);    console.log('req:', req);    const title = body.title;    const content = body.content;    const featured = body.featured;    const updates = {        title,        content,        featured    };    if (req.file) {        const image = req.file.filename;        updates.image = image;    }    Post.findOneAndUpdate(id, {            $set: updates        }, {            new: true        }).then(post => {            req.flash('success', 'Edits submitted successfully');            res.redirect('/posts');        })        .catch(err => {            return req.flash('error', 'Unable to edit article');        });});


const multer = require('multer'); var storage = multer.diskStorage({    destination: (req, file, callback) => {    callback(null, 'public/uploads/') }, filename: (req, file, callback) => {    var filetype = file.mimetype;    var fileformate = filetype.split("/")[1];    callback(null, Date.now() + '.' + fileformate); }});var upload = multer({ storage: storage });