I'm having trouble uploading multiple images with multer

Model

const mongoose  = require ('mongoose')

const CakeBlogDetail = mongoose.model('CakeBlogDetail', new mongoose.Schema({
    image:String,
    description:String,
    menuTitle:String,
    menuDesc:String,
    guestTitle:String,
    guestDesc:String,
    blogID:{type:mongoose.Schema.Types.ObjectId,ref:'CakeBlogs'}
}))

module.exports = CakeBlogDetail

Controller


const CakeBlogDetail = require('../models/blogDetail.model')

const fs = require('fs')
const path = require('path')

const CakeBlogDetailController = {
    post: async(req,res)=>{
        const url = req.protocol + '://' + req.get('host');

        const newBlogDetail = new CakeBlogDetail({
            blogID:req.body.blogID,
            image: url + '/detailimages/'+req.body.filename,
            description:req.body.description,
            menuTitle:req.body.menuTitle,
            menuDesc:req.body.menuDesc,
            guestTitle:req.body.guestTitle,
            guestDesc:req.body.guestDesc,
        })
        await newBlogDetail.save()
        res.status(201).send('detail created');
         console.log('req.file'+req.file)
    },

    getAll: async(req,res)=>{
        const AllBlogDetails = await CakeBlogDetail.find();
        res.status(200).send({
            data:AllBlogDetails,
            message:'blogs get succesfully'
        })
    },

    getById: async(req,res)=>{
        const id = req.params.id;
        CakeBlogDetail.findById(id).then((blog)=>{
            res.status(200).send({
                data:blog,
                message:'blog get succesfully'
            })
        }).catch((err)=>{
            res.send('data not found')
        })
    },

    delete: async(req,res)=>{
        const id = req.params.id;
        const deletedBlog = await CakeBlogDetail.findByIdAndDelete(id);
        const idx = deletedBlog.image.indexOf("detailimages/")
        const imageName = deletedBlog.image.substr(idx)
        
        fs.unlinkSync('./'+imageName)
        if(deletedBlog === undefined){
            res.status(404).send('blog not found');
        }
        else{
            res.status(203).send({
                data:deletedBlog,
                message:'blog deleted succesfully'
            })
        }
    },

    edit: async (req,res)=>{
        const id = req.params.id;
        const description = req.body.description;
        const menuTitle = req.body.menuTitle;
        const menuDesc = req.body.menuDesc;
        const guestTitle = req.body.guestTitle;
        const guestDesc = req.body.guestDesc;

        let updatedBlog = await CakeBlogs.findById(id);

        if(!updatedBlog){
            return res.status(404).send("blog not found")
        }

        const idx = updatedBlog.image.indexOf("detailimages/");
        const imageName = updatedBlog.image.substr(idx);
      
        if (req.file) {
         
            fs.unlinkSync('./' + imageName);
        
            const updatedUrl = req.protocol + '://' + req.get('host');
            updatedBlog.image = updatedUrl + '/detailimages/' + req.file.filename;
          }

          updatedBlog.description = description;
          updatedBlog.menuTitle = menuTitle;
          updatedBlog.menuDesc = menuDesc;
          updatedBlog.guestTitle = guestTitle;
          updatedBlog.guestDesc = guestDesc;


          await updatedBlog.save();

          res.status(203).send({
            data: updatedBlog,
            message: "blog updated successfully",
          });

    }

}

module.exports = CakeBlogDetailController

Router


const express = require('express');
const blog_detail_router = express.Router();
const CakeBlogDetailController = require('../controllers/blogDetail.controller')
const upload = require('../helper/detailupload');


blog_detail_router.post('/',upload.any('image'),CakeBlogDetailController.post)


blog_detail_router.get('/',CakeBlogDetailController.getAll)


blog_detail_router.get('/:id',CakeBlogDetailController.getById)


blog_detail_router.delete('/:id',CakeBlogDetailController.delete)


blog_detail_router.put('/:id',upload.any('image'),CakeBlogDetailController.edit)


module.exports = blog_detail_router

multer upload


const multer = require('multer')
const uuid = require('uuid')

const DIR = './detailimages/';
const storage = multer.diskStorage({
    destination: (req, files, cb) => {
        cb(null, DIR);
    },
    filename: (req, files, cb) => {
        const fileName = files.originalname.toLowerCase().split(' ').join('-');
        cb(null, uuid.v4() + '-' + fileName)
    }
});

module.exports =  upload = multer({
    storage: storage,
    fileFilter: (req, files, cb) => {
        if (files.mimetype == "image/png" || files.mimetype == "image/jpg" || files.mimetype == "image/jpeg") {
            cb(null, true);
        } else {
            cb(null, false);
            return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
        }
    }
});

index.js

const express = require('express');

const app = express();

const cors = require('cors');

const bodyParser = require('body-parser');

const dotenv = require('dotenv');

const mongoose = require('mongoose');

const admin_router = require('./routes/admin.routes')

const logo_router = require('./routes/navLogo.routes');

const slider_router = require('./routes/slider.routes');

const service_router = require('./routes/services.routes');

const category_router = require('./routes/categories.routes');

const work_router = require('./routes/works.routes');

const prices_router = require('./routes/prices.routes');

const team_router = require('./routes/team.routes');

const skill_router = require('./routes/skills.routes');

const progress_router = require('./routes/progress.routes');

const blog_router = require('./routes/blogs.routes');

const blog_slider_router = require('./routes/blogSlider.routes');

const blog_detail_router = require('./routes/blogDetail.routes');

dotenv.config();

app.use(bodyParser.json());

app.use(cors());

app.use('/api', admin_router)

app.use('/images', express.static('images'))

app.use('/detailimages', express.static('detailimages'))

app.get('/api', (req, res) => {

res.send('Hello World!')

})

app.use('/api/logo', logo_router)

app.use('/api/sliders', slider_router)

app.use('/api/services', service_router)

app.use('/api/categories', category_router)

app.use('/api/works', work_router)

app.use('/api/prices', prices_router)

app.use('/api/team', team_router)

app.use('/api/skills', skill_router)

app.use('/api/progress', progress_router)

app.use('/api/blogs', blog_router)

app.use('/api/blogslider', blog_slider_router)

app.use('/api/blogdetail', blog_detail_router)

DB_CONNECTION = process.env.DB_CONNECTION

DB_PASSWORD = process.env.DB_PASSWORD

mongoose.connect(DB_CONNECTION.replace("<password>", DB_PASSWORD)).then(()=>{

console.log('MongoDB Connected')

})

PORT = process.env.PORT

app.listen(PORT, () => {

console.log(`Example app listening on port ${PORT}`)

})

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.