File Upload with Multer
Configure Multer for disk storage with file type validation, size limits, and unique filenames for Express.
import multer from 'multer';
import path from 'path';
import crypto from 'crypto';
const ALLOWED_TYPES = [
'image/jpeg',
'image/png',
'image/webp',
'application/pdf',
];
const MAX_SIZE = 5 * 1024 * 1024; // 5 MB
const storage = multer.diskStorage({
destination: (_req, _file, cb) => cb(null, 'uploads/'),
filename: (_req, file, cb) => {
const unique = crypto.randomBytes(16).toString('hex');
const ext = path.extname(file.originalname);
cb(null, `${unique}${ext}`);
},
});
export const upload = multer({
storage,
limits: { fileSize: MAX_SIZE },
fileFilter: (_req, file, cb) => {
if (ALLOWED_TYPES.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error(`Invalid file type: ${file.mimetype}`));
}
},
});
// Usage:
// app.post('/upload', upload.single('avatar'), (req, res) => {
// res.json({ path: req.file?.path });
// });Sponsored
Cloudinary — Image & video management
Use Cases
- Profile avatar uploads
- Document attachment handling
- Image processing pipelines
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Stream File Download
Express handler that streams a file to the client with proper headers, range support, and error handling.
JWT Verify Middleware
Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.
In-Memory Rate Limiter for Express
Token bucket rate limiter middleware for Express with configurable window and max requests per IP.
Async Error Handler Wrapper
Higher-order function that wraps async Express route handlers and forwards rejected promises to error middleware.