Express.js / File Uploads and Multer in Express.js

Validating File Formats and Sizes

This tutorial will teach you how to validate file formats and sizes using Multer in Express.js. We'll look at the different options provided by Multer for validation, and how to u…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores handling file uploads using Multer in Express applications.

1. Introduction

In this tutorial, we aim to learn how to validate file formats and sizes using Multer in Express.js. Multer is a node.js middleware used for handling multipart/form-data, primarily used for uploading files. We will learn how to control which files are allowed to be uploaded and their maximum size.

By the end of this tutorial, you should be able to:
- Understand how to use Multer to upload files in Express.js.
- Validate file formats and sizes using Multer.
- Implement these techniques in your Express.js app.

Prerequisites:
- Basic understanding of JavaScript.
- Familiarity with Node.js and Express.js.

2. Step-by-Step Guide

Multer is a middleware that processes multipart/form-data. It is mostly used for uploading files. Multer adds a body object and a file or files object to the request object. The body object contains the values of the text fields of the form, the file or files object contains the files uploaded via the form.

To validate file formats and sizes, you can customize the storage options or use the fileFilter and limits options.

3. Code Examples

Example 1: Basic file upload with Multer

First, let's look at a simple example of uploading a file with Multer.

const express = require('express');
const multer  = require('multer');
const upload = multer({ dest: 'uploads/' });

const app = express();

app.post('/upload', upload.single('file'), (req, res) => {
  res.send('File uploaded successfully.');
});

In this code:

  • We import the required modules.
  • We set up Multer to save uploaded files to the 'uploads' directory.
  • We create an Express route for file upload. The upload.single('file') middleware processes the file upload.

Example 2: Validating file format

Now, let's add a fileFilter to validate the file format.

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function(req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
});

const fileFilter = function(req, file, cb) {
  // Only allow files with .jpg, .jpeg, .png, .gif extensions
  if (file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg' || file.mimetype === 'image/png' || file.mimetype === 'image/gif') {
    cb(null, true);
  } else {
    cb(new Error('Invalid file type, only JPG, JPEG, PNG and GIF is allowed!'), false);
  }
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter
});

app.post('/upload', upload.single('file'), (req, res) => {
  res.send('File uploaded successfully.');
});

In this code:

  • We define a custom storage option that includes a fileFilter.
  • The fileFilter function checks the mimetype of the uploaded file and only allows certain types.

Example 3: Validating file size

Finally, let's add a limits option to validate the file size.

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 1024 * 1024 * 5 // we are allowing only up to 5mb files
  }
});

In this code:

  • We add a limits option to the Multer configuration.
  • The fileSize limit is set to 5MB.

4. Summary

In this tutorial, we learned how to:

  • Use Multer to handle file uploads in an Express.js app.
  • Validate file formats and sizes using Multer's fileFilter and limits options.

To continue learning, you can explore more about Multer's options, such as inMemoryStorage for storing the files in memory as Buffer objects.

5. Practice Exercises

  1. Modify the fileFilter function to allow PDF files.
  2. Set a fileSize limit of 1MB.
  3. Create a route for uploading multiple files at once.

Solutions:

  1. To allow PDF files, add 'application/pdf' to the list of allowed mimetypes in the fileFilter function.
  2. To set a fileSize limit of 1MB, change the limits option to { fileSize: 1024 * 1024 }.
  3. To create a route for uploading multiple files, use upload.array('files') instead of upload.single('file'). The 'files' field should contain an array of files.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help