Handle file uploads with validation
Quick Answer
Configure Multer with `diskStorage` for unique filenames, a `fileFilter` that validates MIME type and extension, and a `limits.fileSize` cap — all before files are written to disk.
1import multer from 'multer';
2import path from 'path';
3
4const storage = multer.diskStorage({
5 destination: './uploads/',
6 filename: (req, file, cb) => {
7 const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
8 cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
9 }
10});
11
12const upload = multer({
13 storage,
14 limits: { fileSize: 5 * 1024 * 1024 },
15 fileFilter: (req, file, cb) => {
16 const allowedTypes = /jpeg|jpg|png|gif|pdf/;
17 const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
18 const mimetype = allowedTypes.test(file.mimetype);
19
20 if (extname && mimetype) {
21 return cb(null, true);
22 }
23 cb(new Error('Invalid file type'));
24 }
25});
26
27export default upload;Multer is the standard Express middleware for handling multipart/form-data file uploads. This configuration uses disk storage with a unique filename generator to prevent collisions, a 5MB file size limit, and a fileFilter that validates MIME types and extensions — rejecting invalid files before they are written to disk.
Use the `multer-s3` storage engine instead of `multer.diskStorage`. It streams files directly to an S3 bucket without writing them to the local filesystem.
This free typescript code snippet for file upload handler is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this advanced-level example will help you implement file upload handler quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.