Multer File Filtering: Accept or Reject Files

When handling file uploads, it's important to control what kind of files users can upload. Multer provides a fileFilter option to accept or reject files based on custom logic.

What is fileFilter in Multer?

fileFilter is a function in Multer configuration that allows you to:

It runs before the file is stored.

How to allow only specific file types in Multer?

You can restrict uploads by checking the file’s MIME type or extension.

Example (allow only images):

const multer = require("multer");

const fileFilter = (req, file, cb) => {
  if (file.mimetype.startsWith("image/")) {
    cb(null, true);
  } else {
    cb(new Error("Only image files are allowed"), false);
  }
};

const upload = multer({ fileFilter });

How to reject files in Multer upload?

To reject a file, call the callback with:

Example:

const fileFilter = (req, file, cb) => {
  if (file.mimetype === "application/pdf") {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

How to validate file type before upload?

You can validate using:

Example (images + PDF):

const fileFilter = (req, file, cb) => {
  const allowedTypes = ["image/jpeg", "image/png", "application/pdf"];

  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error("Invalid file type"), false);
  }
};

What happens when a file is rejected?

If a file is rejected:

Handling errors:

app.post("/upload", upload.single("file"), (req, res) => {
  if (!req.file) {
    return res.status(400).json({
      message: "File rejected",
    });
  }

  res.send("File uploaded successfully");
});

Complete Example

const express = require("express");
const multer = require("multer");

const app = express();

const fileFilter = (req, file, cb) => {
  if (file.mimetype.startsWith("image/")) {
    cb(null, true);
  } else {
    cb(new Error("Only images allowed"), false);
  }
};

const upload = multer({ fileFilter });

app.post("/upload", upload.single("file"), (req, res) => {
  if (!req.file) {
    return res.status(400).send("Invalid file type");
  }

  res.json({
    message: "File uploaded successfully",
    file: req.file,
  });
});

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

Key Takeaways