Back to all snippets
Library/Node.js/File Upload Handler
typescriptadvancedfilesuploadvalidation

How to implement File Upload Handler in Typescript

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.

Code Snippet

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;

What is File Upload Handler?

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.

How It Works

  1. 1`multer.diskStorage` controls where files are saved and what they are named.
  2. 2The filename callback appends a timestamp + random number to prevent collisions.
  3. 3`fileFilter` checks both the file extension and MIME type before accepting the upload.
  4. 4`limits.fileSize` enforces a maximum file size — Multer rejects oversized files automatically.

Common Use Cases

  • Profile photos - Accept JPEG and PNG avatar uploads
  • Document management - Upload PDF files with size restrictions
  • Product images - Handle e-commerce product image uploads
  • CSV import - Accept spreadsheet file uploads for data import

Key Benefits

  • Validates MIME type and file extension before saving
  • Unique filename prevents overwrites and path traversal issues
  • Configurable file size limit per upload route
  • Integrates directly as Express route middleware

Common Mistakes to Avoid

  • Trusting only the file extension — always check MIME type too since extensions can be spoofed.
  • Storing uploads in the project directory in production — use an object store like S3 with `multer-s3` instead.
  • Not limiting file count — `limits.files` caps the number of files in a single request.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more typescript examples

Frequently Asked Questions

How do I upload files directly to S3 instead of 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.

About This Typescript Code Snippet

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.

Tags: files, upload, validation  | Language: typescript  | Difficulty: advanced  | Category: Node.js

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.