Multer File Type Validation Tutorial with Example

Last updated on: by Digamber
Today we are going to learn, how to validate file types while uploading files with Multer. In this tutorial, we will understand how to handle file validation errors for various file types such as .jpg, .jpeg, and .png.

Multer is a node.js middleware it helps in handling multipart/form-data. It is mainly used for uploading files. To build the basic file uploading system, follow this tutorial: Angular 8 Node & Express JS File Upload Tutorial

First, Run command to install Multer middleware.

npm install multer

Then, import Multer middleware to work with multipart form-data.

let multer = require('multer');

Define the path to folder where we will keep all the files or assets.

// File upload folder
const DIR = './public/';

We have defined the `diskstorage` method with multer, and It gives the complete control on the files we upload to the `public` (any name can be used) folder.

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, DIR);
  },
  filename: (req, file, cb) => {
    const fileName = file.originalname.toLowerCase().split(' ').join('-');
    cb(null, fileName)
  }
});

We declared the destination method with req, file, cb middleware, and passed the folder path where all the files are stored after uploading. Here cb refers to callback, and it’s a built-in method of Multer.

Then, we declared the filename method inside the diskStorage engine. This method returns the file name of the uploaded file in the destination folder.

Multer File Type Validation

Define multer object and pass the storage inside as the first property within the multer object. Then we will use the fileFilter method to validate file types in Multer. The fileFilter method is a built-in method which comes with Multer middleware. We declared the req, file, and cb middlewares with fileFilter method.

var upload = multer({
  storage: storage,
  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('Only .png, .jpg and .jpeg format allowed!'));
    }
  }
});

Declare the if statement along with the correct file.mimetype options. In this tutorial we are validating .jpeg, .jpg and .png extension.

If the condition is true, then call the cb function and pass the null and true parameter. And, If the condition is false then return the error message along with the cb method with null and false parameters.

Verify Multer File Type Validation

Finally, we will verify the Multer file type validation by using the Express API. If upload the file with the declared file extensions (jpg, jpeg or png), then Multer will store the file in the `public` folder else it will throw the validation error.

// POST
app.post('/add', upload.single('image'), (req, res, next) => {
  const user = new User({
    _id: new mongoose.Types.ObjectId(),
    name: req.body.name,
    imageURL: req.file.path
  });
  user.save().then(result => {
    res.status(201).json({
      message: "User registered successfully!",
    })
  })
})

Finally, we have completed the Multer file validation for .jpeg, .jpg and .png extension. I hope you enjoyed this tutorial if you want to know more about Multer. Please checkout their official documentation here.

Digamber

A Full-stack developer with a passion to solve real world problems through functional programming.