Search code examples
javascriptnode.jsamazon-s3multermulter-s3

How to validate different file types in multer s3?


I want to handle and validate video and image files from multer.Multer middleware can have 1 video file and 10 images.I want to validate whether it have only 10 images and 1 video file.I also want validate file size.I want video to have 25mb and images to have 5mb.But limits options only take one file size.Here it valdating for 5mb file.How do I validate video,which should be of 25mb.

const multerS3 = require('multer-s3');
const multer = require('multer');
const AWS = require('aws-sdk');

const s3 = new AWS.S3({
  accessKeyId: process.env.ACCESS_KEY_ID,
  secretAccessKey: process.env.SECRET_ACCESS_KEY,
  region: process.env.REGION
});

const fileFilter = (req, file, cb) => {
  console.log(file.mimetype);
  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
    cb(null, true);
  } else {
    cb(null, false);
   }
  cb(null, true);
};

const middleware = function(req, res, next) {
  let upload = multer({
    storage: multerS3({
      s3: s3,
      bucket: process.env.BUCKET_NAME,
      acl: 'public-read',
      cacheControl: 'max-age=31536000',
      contentType: multerS3.AUTO_CONTENT_TYPE,
      metadata: function(req, file, cb) {
        // console.log('in callback');
        cb(null, { fieldName: file.fieldname });
      },
      key: function(req, file, cb) {
        // console.log('in callback 2');
        cb(null, Date.now().toString() + '-' + file.originalname);
      }
    }),
    fileFilter: fileFilter,
    limits: {
      fileSize: 1024 * 1024 * 5
    }
  }).fields([
    { name: 'images', maxCount: 10 },
    { name: 'video', maxCount: 1 }
  ]);

  upload(req, res, function(err) {
    console.log(err);
    next();
  });
};

module.exports = middleware;


Solution

  • Currently, it is not supported in multer,

    You can follow the discussion on GitHub for more details:

    issue-569,
    issue-833,
    issue-314