Validating File Formats and Sizes

Tutorial 3 of 5

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.