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:
- Accept valid files
- Reject unwanted files
- Validate uploads before saving
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:
- An error →
cb(new Error("message"), false) - Or simply
cb(null, false)
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:
file.mimetypefile.originalname
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:
- It is not stored
req.fileorreq.fileswill be undefined or empty- An error may be thrown if provided
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
fileFiltercontrols which files are accepted- Use MIME type checks for validation
- Reject files using
cb(null, false)or an error - Always handle rejected file cases in your route