skip to Main Content

I am working with Nodejs and using expressjs framework,Right now i am trying to upload image using Api but
i want two things

1) if image extension is not "jpg,png,gif" then error message should display

Here is my current code

var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
 filename: function (req, file, callback) {
     var sizeOf = require('image-size');
        var sizeOf = require('image-size');
        const originalname = file.originalname;
        const fileExt = originalname.split(".").pop();
       const excatName = originalname.split(".").slice(0, -1).join(".");
       console.log("mimetype is " + file.mimetype); // GETTING FILE EXTENSION NAME
       callback(null, excatName + "-" + Date.now().toString() + "." + fileExt);
      },
});
var upload = multer({ storage: storage }).single('userPhoto');
 const uploadavatar = function (req, res) {
    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file." + err);
        }
        res.end("File is uploaded");
    });
};
 

2

Answers


  1. const { promisify } = require('util')
    const sizeOf = promisify(require('image-size'))
    
    var upload = multer({
      storage: multer.diskStorage({
          destination: function(req, file, callback) {
              callback(null, './uploads');
          },
          filename: function(req, file, callback) {
              let ogNameArray = file.originalname.split(".");
              callback(null, ogNameArray[0] + "-" + Date.now().toString() + "." + ogNameArray[ogNameArray.length - 1]);
          }
      })
    }, {
      fileFilter: (req, file, cb) => {
          const filetypes = /jpeg|jpg|png|gif/;
          const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
          const mimetype = filetypes.test(file.mimetype);
          if(mimetype && extname){ 
            sizeOf('./uploads/' + file.originalname)
            .then(dimensions => { 
              //validate your dimention and return true false based on this
              console.log(dimensions.width, dimensions.height) 
              cb(null, true);
            })
            .catch(err => {
              // invalid file format.
              console.error(err);
              cb(null, false);
            })        
          }else{
            cb(null, false)
          }      
      }
    }, ).single('userPhoto');
    
    const uploadavatar = function(req, res) {
      upload(req, res, function(err) {
          if (err) {
              return res.end("Error uploading file." + err);
          }
          res.end("File is uploaded");
      });
    };
    
    Login or Signup to reply.
  2. you can pass a filter function to multer params object and with help of filter you can exclude mimetype and a create a error : –

    var storage =   multer.diskStorage({
      destination: function (req, file, callback) {
        callback(null, './uploads');
      },
     filename: function (req, file, callback) {
         var sizeOf = require('image-size');
            var sizeOf = require('image-size');
            const originalname = file.originalname;
            const fileExt = originalname.split(".").pop();
           const excatName = originalname.split(".").slice(0, -1).join(".");
           console.log("mimetype is " + file.mimetype); // GETTING FILE EXTENSION NAME
           callback(null, excatName + "-" + Date.now().toString() + "." + fileExt);
          },
    });
    
     var multerFilter = (req, file, cb) => {
      const memeT = file.mimetype.split('/')[1];
      const restrictToMemeType = ['jpg', 'png', 'gif'];
      if (restrictToMemeType.includes(memeT)) {
        cb(null, true);
      } else {
        cb(new Error('sorry invalid meme type'), false);
      }
    };
    var upload = multer({ storage: storage,fileFilter: multerFilter }).single('userPhoto');
     const uploadavatar = function (req, res) {
        upload(req,res,function(err) {
            if(err) {
                return res.end("Error uploading file." + err);
            }
            res.end("File is uploaded");
        });
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search