Backend Development

How Do You Upload Files Using Multer? A Beginner-Friendly Guide

Have you ever built a profile page where users can upload their profile pictures? Or perhaps you're developing a blog where authors can upload featured images,…

D
DevByteTechnical Author
Published
9 min read0 views
How Do You Upload Files Using Multer? A Beginner-Friendly Guide

Have you ever built a profile page where users can upload their profile pictures? Or perhaps you're developing a blog where authors can upload featured images, documents, or other media files?

If you're working with Node.js and Express.js, handling file uploads is a common requirement. However, uploading files is different from sending ordinary JSON data because files contain binary data that must be transmitted and processed correctly.

This is where Multer comes in.

Multer is a popular Node.js middleware that simplifies handling multipart/form-data, the encoding commonly used when submitting files through HTML forms.

In this guide, we'll learn what Multer is, how it works, how to upload single and multiple files, how to validate uploads, and how to integrate it into a real Express.js application.

1. What Is Multer in Node.js?

Multer is middleware for Express.js that processes incoming requests containing multipart/form-data.

When a user selects a file and submits a form, the browser can send the file alongside other form fields. Multer parses this request and makes the uploaded file information available to your Express.js route handler.

For example, imagine a user submits a profile update form containing:

  • Name

  • Email

  • Profile picture

The name and email are regular text fields, while the profile picture is a file.

Multer helps you process both types of input in the same request.

Why Do We Need Multer?

Express.js can parse JSON requests using express.json(), but that middleware does not handle multipart file uploads.

Multer fills this gap by processing multipart form data and exposing the results through properties such as:

  • req.file for a single uploaded file.

  • req.files for multiple uploaded files.

  • req.body for text fields included in the multipart request.

Multer also supports different storage strategies, file filtering, and file size limits.

Important: Multer is designed specifically for multipart requests. It does not process every possible file-upload format or replace JSON body parsing.

2. Install Multer in Your Express.js Project

Let's start by creating a simple Express.js application.

First, create a project:

mkdir multer-file-upload
cd multer-file-upload
npm init -y

Install Express.js and Multer:

npm install express multer

Create an index.js file:

const express = require("express");
const multer = require("multer");
const path = require("path");

const app = express();

app.use(express.json());

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

Here:

  • express creates the web server.

  • multer processes multipart file uploads.

  • path helps work with filesystem paths.

We will use Multer to handle file uploads in the following examples.

3. Upload a Single File Using Multer

Let's begin with the most common use case: uploading a single file.

Suppose you're building a profile page where users can upload a profile picture.

Step 1: Configure Storage

Multer provides a storage engine called diskStorage, which allows you to control where files are saved and how their filenames are generated.

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads/");
  },

  filename: (req, file, cb) => {
    const uniqueName =
      `${Date.now()}-${Math.round(Math.random() * 1e9)}` +
      path.extname(file.originalname);

    cb(null, uniqueName);
  },
});

Let's understand the configuration.

destination

This function specifies the directory where uploaded files will be saved.

In this example, files are stored in the uploads/ directory.

filename

This function determines the name assigned to each uploaded file.

We generate a unique-looking filename using a timestamp and a random number while preserving the original file extension.

This helps reduce filename collisions and prevents users from directly choosing the stored filename.

However, this example is not a complete security guarantee. Production applications should also validate file types and extensions and use a cryptographically secure random identifier when appropriate.

Step 2: Create the Upload Directory

Create the directory before starting the server:

mkdir uploads

You can also create it programmatically using Node.js's fs module.

For a simple application, manually creating the directory is sufficient.

Step 3: Initialize Multer

Now pass the storage configuration to Multer:

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

This creates a Multer instance that uses the configured storage engine.

Step 4: Create the Upload Route

Use Multer's single() method to accept one file:

app.post(
  "/upload",
  upload.single("profilePicture"),
  (req, res) => {
    if (!req.file) {
      return res.status(400).json({
        message: "Please upload a file",
      });
    }

    res.status(200).json({
      message: "File uploaded successfully",
      file: req.file,
    });
  }
);

Notice this line:

upload.single("profilePicture")

The string "profilePicture" must match the name of the file field sent by the client.

When the upload succeeds, Multer makes the uploaded file's information available through req.file.

For example, the response may contain:

{
  "message": "File uploaded successfully",
  "file": {
    "fieldname": "profilePicture",
    "originalname": "avatar.png",
    "encoding": "7bit",
    "mimetype": "image/png",
    "destination": "uploads/",
    "filename": "1734567890-123456789.png",
    "path": "uploads/1734567890-123456789.png",
    "size": 24576
  }
}

The exact values depend on the uploaded file.

Remember that req.file contains file metadata, not the complete file contents.

4. Upload Multiple Files Using Multer

What if users need to upload several images at once?

For example, an e-commerce application might allow sellers to upload multiple product images.

Multer provides several methods for handling multiple files.

Method 1: Upload Multiple Files with array()

Use upload.array() when the client uploads multiple files through the same field.

app.post(
  "/upload-multiple",
  upload.array("images", 5),
  (req, res) => {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({
        message: "Please upload at least one image",
      });
    }

    res.status(200).json({
      message: "Files uploaded successfully",
      files: req.files,
    });
  }
);

In this example:

upload.array("images", 5)
  • "images" is the expected field name.

  • 5 is the maximum number of files accepted through that field.

Multer places the uploaded files in req.files.

You can loop through the array to save file information in your database or associate the files with a particular product.

Method 2: Upload Files from Different Fields with fields()

Sometimes a form contains different file inputs.

For example:

  • profilePicture

  • resume

  • certificates

You can handle these fields using upload.fields():

app.post(
  "/upload-documents",
  upload.fields([
    { name: "profilePicture", maxCount: 1 },
    { name: "resume", maxCount: 1 },
    { name: "certificates", maxCount: 3 },
  ]),
  (req, res) => {
    res.status(200).json({
      message: "Files uploaded successfully",
      files: req.files,
    });
  }
);

In this case, req.files is an object whose keys correspond to the configured field names.

For example:

req.files.profilePicture;
req.files.resume;
req.files.certificates;

Each property contains an array of uploaded files.

Multer Methods at a Glance

Method

Purpose

Result

single()

Upload one file

req.file

array()

Upload multiple files through one field

req.files as an array

fields()

Upload files through multiple named fields

req.files as an object

none()

Accept only text fields in multipart data

req.body

any()

Accept files from any field

req.files as an array

Use any() cautiously. Avoid applying it globally or using it on routes that do not require arbitrary file fields. Prefer explicit upload fields whenever possible.

5. Validate Files Before Uploading

File uploads introduce security risks. Attackers may attempt to upload unexpectedly large files, malicious content, or files that your application was never designed to accept.

Multer supports fileFilter for basic filtering and limits for restricting resource usage.

Let's create a configuration that accepts only certain image MIME types and limits file sizes.

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads/");
  },

  filename: (req, file, cb) => {
    const uniqueName =
      `${Date.now()}-${Math.round(Math.random() * 1e9)}` +
      path.extname(file.originalname);

    cb(null, uniqueName);
  },
});

const upload = multer({
  storage,

  limits: {
    fileSize: 2 * 1024 * 1024,
    files: 5,
  },

  fileFilter: (req, file, cb) => {
    const allowedTypes = [
      "image/jpeg",
      "image/png",
      "image/webp",
    ];

    if (allowedTypes.includes(file.mimetype)) {
      return cb(null, true);
    }

    cb(new Error("Only JPEG, PNG, and WebP images are allowed"));
  },
});

This configuration:

  • Limits individual files to 2 MB.

  • Limits the number of files to five.

  • Allows only the listed MIME types.

However, there is an important security detail: the MIME type is supplied by the client and can be forged.

For production applications, do not rely exclusively on file.mimetype or the original filename extension. Verify the actual file format using appropriate content inspection, enforce upload limits, and consider scanning files where appropriate.

Also, remember that the files limit applies to files processed by that Multer instance. Configure field-specific limits when necessary.

6. Handle Multer Errors Properly

What happens when a user uploads a file larger than the permitted size?

Or when a request contains more files than allowed?

Multer can generate errors such as LIMIT_FILE_SIZE and LIMIT_FILE_COUNT.

You should handle these errors gracefully rather than returning a generic server error.

For example:

app.post("/upload", (req, res) => {
  upload.single("profilePicture")(req, res, (err) => {
    if (err instanceof multer.MulterError) {
      if (err.code === "LIMIT_FILE_SIZE") {
        return res.status(400).json({
          message: "File size exceeds the allowed limit",
        });
      }

      return res.status(400).json({
        message: "File upload failed",
        error: err.code,
      });
    }

    if (err) {
      return res.status(400).json({
        message: err.message || "Invalid file upload",
      });
    }

    if (!req.file) {
      return res.status(400).json({
        message: "Please select a file",
      });
    }

    return res.status(200).json({
      message: "File uploaded successfully",
      filename: req.file.filename,
    });
  });
});

This pattern lets you handle Multer errors and other upload-related errors within the route.

In a larger Express.js application, you can extract this logic into reusable middleware or integrate it with your centralized error-handling system.

Also, consider cleaning up partially uploaded files when a later validation step fails.

7. How to Upload Files from Postman

Once your endpoint is ready, you can test it using Postman.

Follow these steps:

  1. Open Postman.

  2. Select the POST method.

  3. Enter your endpoint, such as http://localhost:3000/upload.

  4. Open the Body tab.

  5. Select form-data.

  6. Add a key named profilePicture.

  7. Change the key's type from Text to File.

  8. Select a file from your computer.

  9. Click Send.

Make sure the key name matches the field name in your Multer middleware:

upload.single("profilePicture")

For multiple uploads, use a key such as images and select multiple files if your Postman version supports it.

You can also submit regular text fields alongside uploaded files. Multer makes these fields available through req.body.

8. Where Should You Store Uploaded Files?

In the examples above, files are stored locally in an uploads/ directory.

This is useful for learning and small applications, but local storage has limitations.

For production applications, consider the following options:

Local storage: Suitable for local development or applications with a properly managed persistent filesystem.

Amazon S3: Useful for storing files in scalable object storage. Your application can store the resulting object key or URL in a database.

Cloudinary: A popular option for managing images and other supported media, with additional image-processing capabilities.

Other object storage services: Depending on your infrastructure, you can use compatible services to store and serve uploaded files.

If your application runs on serverless infrastructure or multiple application instances, relying on local disk storage may cause problems because files might not persist or be available across instances.

A common production architecture is:

  1. The user uploads a file.

  2. The application validates the upload.

  3. The file is stored in object storage.

  4. The database stores the file's key, URL, or associated metadata.

  5. The application retrieves the file when needed.

For large files, consider direct-to-object-storage uploads using short-lived, restricted presigned URLs. This can reduce the load on your Express.js server.

Conclusion

Multer makes file uploads straightforward in Node.js and Express.js by handling multipart/form-data and exposing uploaded file information through req.file and req.files.

You can use single() for one file, array() for multiple files in one field, and fields() for uploads across multiple named fields.

However, implementing file uploads involves more than simply saving files to a directory. Always validate incoming data, enforce file size and count limits, verify file contents where appropriate, handle errors correctly, and choose storage that fits your application's deployment environment.

Once you understand these fundamentals, you can build secure file-upload features for profile pictures, blog images, documents, product galleries, and many other real-world applications.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘