Multer — middleware for handling multipart/form-data (file uploads).
1const multer = require("multer");2const path = require("path");34// Storage configuration5const storage = multer.diskStorage({6 destination: (req, file, cb) => cb(null, "uploads/"),7 filename: (req, file, cb) => {8 const unique = Date.now() + "-" + Math.round(Math.random() * 1e9);9 cb(null, unique + path.extname(file.originalname));10 },11});1213// File filter14const fileFilter = (req, file, cb) => {15 const allowed = /jpeg|jpg|png|gif/;16 const ext = allowed.test(path.extname(file.originalname).toLowerCase());17 const mime = allowed.test(file.mimetype);18 cb(null, ext && mime);19};2021const upload = multer({22 storage,23 fileFilter,24 limits: { fileSize: 5 * 1024 * 1024 }, // 5MB25});2627app.post("/upload", upload.single("image"), (req, res) => {28 res.json({ file: req.file });29});
Security considerations: