Search code examples
node.jsamazon-web-servicesexpressamazon-s3multer

Multer limit images accepted


I am working with Multer and Multer S3 to allow users to upload images on a Node project. I am wanting the user to be able to upload 3 images regardless of their size but no more. If a user tries to select say 6 images I get this error page:

Error: Unexpected field
   at makeError

How would I change my code below to not allow a user to select/upload more than 3 images and/or handle the error in a better way.

Partial Code:

router.post("/", upload.array('image', 3), function(req, res, next){

          var filepath = undefined;

          var filepath2 = undefined;

          var filepath3 = undefined;

        if(req.files[0]) {
            filepath = req.files[0].key;
        } 

          if(req.files[1]) {
            filepath2 = req.files[1].key;
        } 

         if(req.files[2]) {
            filepath3 = req.files[2].key;
        }.....

Update:

I added this and now I land on a "too many files" error page if the user tries to upload more than 3. Now I just have to figure out how to redirect if too many files.

  var upload = multer({
    limits : { files: 3 },

Solution

  • I played around with multer and here is something that I was able to get working.

    Define your multer setup like this

    var upload = multer().array('image', 3);
    

    Then modify your function to this,

    router.post("/", function(req, res, next){
       upload(req, res, function (err) {
            if (err) {
               //redirect your user here ...
               return;
            }
    
            //no multer error proceed with your normal operation ...
    
       })
    });