typescriptintermediate

File Upload with Multer

Configure Multer for disk storage with file type validation, size limits, and unique filenames for Express.

typescript
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.