1 year ago

#75499

test-img

gh rah

Expressjs multer middleware save file in dynamic destination

I am using multer with expressjs and I am trying to change the DIR to save images depending on the request to a dynamic destination, my code is working fine but always save images inside the post directory, I'm using this middleware with multi requests.

1- How can I make the directory dynamic! example: to save to ./public/products if req product & save to ./public/posts if req post

2- How to make sure that the file is uploaded to the directory with no errors in the controller! then save the path to the database!

3- Is this the best practice to use multer ! in middleware level!

multer middleware fileUpload.js

 const multer = require("multer");
 const mkdirp = require("mkdirp");
 const fs = require("fs");

 const getDirImage = () => {
// const DIR = './public/uploads/products';
return `./public/posts`;
};
let storage = multer.diskStorage({
destination: (req, file, cb) => {
    console.log(req.params,'&&&&&&&&&&&&',file);

    let DIR = getDirImage();    
    if (!fs.existsSync(DIR)) {
       fs.mkdirSync(DIR, { recursive: true });
    }   
        cb(null, DIR);
},
filename: (req, file, cb) => {
    const fileName = "overDress" + Date.now() + ""  + 
  file.originalname.toLowerCase().split(' ').join('-');
    cb(null, fileName)
},
  });
 const upload = multer({
storage: storage,
limits: {
    fileSize: 1024 * 1024 * 10 //upto 2 megabytes per file.
},
fileFilter: (req, file, cb) => {
    if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || 
 file.mimetype == "image/jpeg") {
        cb(null, true);
    } else {
        cb(null, false);
        return cb(new Error('File types allowed .jpeg, .jpg and .png!'));
    }
   }
   });
   module.exports = upload; 

product.js route

const controller = require('../controllers/product.controller');
import { Router } from 'express'; //import from esm
import upload from '../middleware/fileUpload'
const router = Router();
router
 .get('/', controller.list)
 .post('/', upload.single('image'), controller.create)
 .get('/:id', controller.getOne)
 export default router;

and my create controller:

exports.create = async (req, res, next) => {
const { name, title, description,subtitle} = req.body;
if (!name || !title) {
  return res.status(400).send({
    message: 'Please provide a title and a name to create a product!',
  });
}
try {    
  if (req.file) {
   req.body.image = req.file.destination + '/' + req.file.filename;

  }
  const PRODUCT_MODEL = {
     name: req.body.name,
     title: req.body.title,
     description: req.body.description,
     image: req.body.image,
  };

  try {
    const product = await Product.create(PRODUCT_MODEL);
    console.log('product crerated');
    return res.status(201).json(product);
  } catch (error) {
    console.log(error);
    return res.status(500).send({
    message: 'Something went wrong: ' + error,
  });
  }
} catch (error) {
  return res.status(500).json(error);
}

};

node.js

express

multer

0 Answers

Your Answer

Accepted video resources