File Uploads with Multer
11 min read
File Uploads with Multer
HTML forms and clients that submit multipart/form-data send file payloads that express.json() cannot parse. Multer is the standard middleware for handling these uploads. It can store files in memory or stream them directly to disk.
js
const multer = require("multer");
const path = require("path");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads/"); // relative to project root
},
filename: function (req, file, cb) {
const ext = path.extname(file.originalname);
const unique = Date.now() + "-" + Math.round(Math.random() * 1e9);
cb(null, unique + ext);
}
});
const upload = multer({
storage,
limits: { fileSize: 5 * 1024 * 1024 }, // 5 MB max
fileFilter: function (req, file, cb) {
const allowed = ["image/jpeg", "image/png", "image/webp"];
if (allowed.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error("Only JPEG, PNG, and WebP images are allowed"));
}
}
});
// Single file under the field name "avatar"
app.post("/upload/avatar", upload.single("avatar"), (req, res) => {
if (!req.file) return res.status(400).json({ error: "No file uploaded" });
res.json({ filename: req.file.filename, size: req.file.size });
});
// Up to 5 files under the field name "photos"
app.post("/upload/photos", upload.array("photos", 5), (req, res) => {
res.json({ count: req.files.length });
});For production, avoid storing uploaded files on the local disk — your server may have multiple instances or use ephemeral storage. Stream files directly to object storage such as AWS S3 using multer-s3.
Always validate file.mimetype and set a limits.fileSize cap. Without them, any client can upload arbitrary content and exhaust your disk or memory.
Ready to test yourself?
Practice Express— quiz & coding exercises