Node.js File Uploads - Handling Multipart/Form-Data Safely with Multer

Handling file uploads—such as user avatars, PDF resumes, and product photos—requires parsing multipart/form-data. In this tutorial, you will configure Multer to safely store files to disk, enforce strict file size limits, and validate image MIME types.

Installing Multer

npm install multer

Configuring Multer Disk Storage & Security Guards

// uploadConfig.js
const multer = require('multer');
const path = require('path');
const crypto = require('crypto');

// 1. Configure Storage Engine & Filename Sanitization
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/avatars/'); // Directory where files are stored
  },
  filename: (req, file, cb) => {
    // Generate secure random filename: <uuid><ext>
    const uniqueSuffix = crypto.randomUUID();
    const ext = path.extname(file.originalname).toLowerCase();
    cb(null, `avatar-${uniqueSuffix}${ext}`);
  }
});

// 2. MIME Type Validation Filter
const fileFilter = (req, file, cb) => {
  const allowedMimeTypes = ['image/jpeg', 'image/png', 'image/webp'];

  if (allowedMimeTypes.includes(file.mimetype)) {
    cb(null, true); // Accept file
  } else {
    cb(new Error('Invalid file type: Only JPEG, PNG, and WebP images are allowed!'), false);
  }
};

// 3. Initialize Multer with 2MB Size Limit
const upload = multer({
  storage: storage,
  limits: { fileSize: 2 * 1024 * 1024 }, // 2 Megabytes max
  fileFilter: fileFilter
});

module.exports = upload;

Creating the Upload Endpoint

// server.js
const express = require('express');
const upload = require('./uploadConfig');

const app = express();

// Single file upload endpoint: input field name must be 'avatar'
app.post('/api/users/avatar', upload.single('avatar'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ success: false, error: 'No file uploaded' });
  }

  res.status(200).json({
    success: true,
    message: 'Avatar uploaded successfully!',
    fileDetails: {
      originalName: req.file.originalname,
      savedFilename: req.file.filename,
      sizeInBytes: req.file.size,
      mimetype: req.file.mimetype,
      path: req.file.path
    }
  });
});

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is Multer and why is it required for file uploads?

Multer is an Express middleware for handling 'multipart/form-data', which is the encoding format browsers use when uploading files through HTML file inputs or FormData objects. Standard express.json() cannot parse multipart file streams.

Q2. How do you restrict file uploads to only image files (JPEG, PNG, WebP)?

Configure the 'fileFilter' function in Multer to inspect 'file.mimetype'. If file.mimetype starts with 'image/' (or matches an allowed list), call 'cb(null, true)'. Otherwise, reject with 'cb(new Error("Only image files are allowed!"), false)'.

Q3. Why should you never trust user-supplied file names directly?

User-submitted file names may contain directory traversal attacks (e.g. '../../etc/cron') or executable extensions (.php, .sh). Always generate a unique sanitized file name using 'crypto.randomUUID()' or timestamps combined with a validated extension.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

File System Module

Manage uploaded files on disk using fs.

Security Best Practices

Prevent malicious file upload exploits.

Express Middleware Deep Dive

Multer functions as Express route middleware.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!