Multiple File Upload in Node.js

Introduction

File upload is a common feature in modern web applications. Sometimes, users need to upload more than one file at a time, such as multiple product images, documents, resumes, or photos.

Node.js allows developers to build multiple file upload functionality using Express.js and Multer. Multer is middleware that handles files submitted through HTML forms using the multipart/form-data encoding type.

What Is Multiple File Upload in Node.js?

Multiple file upload in Node.js is the process of receiving two or more files from a client and storing or processing them on the server in a single HTTP request.

For example, an e-commerce website may allow an administrator to upload several product images at once instead of uploading each image separately.

Common use cases include:

  • Uploading multiple product images.
  • Uploading several documents or PDF files.
  • Uploading photos to a gallery.
  • Submitting multiple attachments through a form.
  • Uploading multiple files for a project or report.

To implement this functionality, developers commonly use Express.js to handle HTTP requests and Multer to process uploaded files.

What Is Multer in Node.js?

Multer is middleware for Express.js that handles multipart/form-data requests. It provides methods for receiving uploaded files and configuring how they are stored.

Some useful Multer methods are:

Method Purpose
upload.single() Accepts one file from a specified field
upload.array() Accepts multiple files from the same field
upload.fields() Accepts files from multiple named fields
multer.diskStorage() Configures file storage on disk
multer.memoryStorage() Stores file data in memory

For uploading several files from one input field, upload.array() is usually the simplest option.

Prerequisites

Before starting this tutorial, make sure you have:

  • Node.js installed on your computer.
  • npm installed.
  • Basic knowledge of JavaScript.
  • Basic knowledge of Express.js and HTML forms.

Step 1: Create a Node.js Project

First, create a project directory and open it in your terminal.


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

The npm init -y command creates a package.json file with default project settings.

Next, install Express and Multer:


npm install express multer

Express will handle HTTP requests, while Multer will process the uploaded files.

Step 2: Create the Project Structure

Create an app.js file and an index.html file. The application will store uploaded files in an uploads directory.


multiple-file-upload/
├── uploads/
├── app.js
├── index.html
├── package.json
├── package-lock.json
└── node_modules/

The example below creates the uploads directory automatically if it does not exist.

Step 3: Create an HTML Form for Multiple File Uploads

Create an index.html file and add the following code:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiple File Upload in Node.js</title>
</head>
<body>
    <h1>Upload Multiple Files</h1>

    <form
        action="/upload"
        method="POST"
        enctype="multipart/form-data"
    >
        <label for="files">Select files:</label>

        <input
            type="file"
            id="files"
            name="files"
            multiple
            required
        >

        <button type="submit">Upload Files</button>
    </form>
</body>
</html>

Let’s understand the important attributes.

Attribute Purpose
action=”/upload” Sends the form to the /upload route
method=”POST” Sends the data using an HTTP POST request
enctype=”multipart/form-data” Allows the form to send file data
type=”file” Displays a file selection control
name=”files” Identifies the file field processed by Multer
multiple Allows users to select multiple files
required Requires the user to select at least one file

The multiple attribute is important because it allows users to select several files in a single form submission.

Step 4: Configure Multer for Multiple File Uploads

Now create the app.js file and configure Multer.


const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { randomUUID } = require('crypto');

const app = express();
const PORT = 3000;

const uploadDir = path.join(__dirname, 'uploads');

fs.mkdirSync(uploadDir, { recursive: true });

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

    filename: (req, file, cb) => {
        const extension = path.extname(file.originalname).toLowerCase();
        cb(null, `randomUUID(){extension}`);
    }
});

const allowedExtensions = new Set([
    '.jpg',
    '.jpeg',
    '.png',
    '.pdf'
]);

const allowedMimeTypes = new Set([
    'image/jpeg',
    'image/png',
    'application/pdf'
]);

const fileFilter = (req, file, cb) => {
    const extension = path.extname(file.originalname).toLowerCase();

    if (
        allowedExtensions.has(extension) &&
        allowedMimeTypes.has(file.mimetype)
    ) {
        return cb(null, true);
    }

    cb(new Error('Only JPG, PNG, and PDF files are allowed.'));
};

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 5 * 1024 * 1024,
        files: 5
    },
    fileFilter: fileFilter
});

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});

app.post('/upload', upload.array('files', 5), (req, res) => {
    if (!req.files || req.files.length === 0) {
        return res.status(400).send('Please select at least one file.');
    }

    const uploadedFiles = req.files
        .map(file => `<li>file.filename({file.size} bytes)</li>`)
        .join('');

    res.send(`
        <h2>Files uploaded successfully!</h2>
        <p>Total files: req.files.length</p><ul>{uploadedFiles}</ul>
        <a href="/">Upload more files</a>
    `);
});

app.use((err, req, res, next) => {
    if (err instanceof multer.MulterError) {
        if (err.code === 'LIMIT_FILE_SIZE') {
            return res.status(413).send(
                'Each file must not exceed 5 MiB.'
            );
        }

        if (err.code === 'LIMIT_FILE_COUNT') {
            return res.status(400).send(
                'You can upload a maximum of 5 files.'
            );
        }

        if (err.code === 'LIMIT_UNEXPECTED_FILE') {
            return res.status(400).send(
                'Unexpected file field or too many files.'
            );
        }

        return res.status(400).send(`Upload error: ${err.message}`);
    }

    if (err) {
        return res.status(400).send(`Upload failed: ${err.message}`);
    }

    next();
});

app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

This example configures Multer to accept up to five files from the files field. Each file is limited to 5 MiB, and the basic filter allows JPG, JPEG, PNG, and PDF files.

The filename is generated using randomUUID() to reduce collisions and avoid using the original filename directly as the storage path.

Important: File extensions and MIME types are not reliable proof of file content. The filter shown here is a basic first check, not a complete security solution.

Step 5: Understand upload.array()

The most important part of the example is:


app.post('/upload', upload.array('files', 5), (req, res) => {
    console.log(req.files);
    res.send('Files received successfully.');
});

The upload.array() method accepts multiple files from the same form field.

Its two arguments are:

  • ‘files’: The name of the HTML input field.
  • 5: The maximum number of files accepted by this middleware.

The field name must match the HTML input’s name attribute.

After Multer processes the request, the uploaded file information becomes available in req.files as an array.

For example, if a user uploads three files, req.files contains information about those three files.

Step 6: Understand req.files

Multer provides information about each uploaded file through the req.files array.

A simplified example looks like this:


[
    {
        fieldname: 'files',
        originalname: 'photo.jpg',
        filename: 'generated-file-id.jpg',
        mimetype: 'image/jpeg',
        size: 120000,
        path: '/project/uploads/generated-file-id.jpg'
    }
]

This is an illustrative example of the file information returned by disk storage.

Some useful properties include:

Property Description
req.file Contains information about a single uploaded file
req.files Contains information about multiple uploaded files
req.file.originalname Original filename supplied by the client
req.file.filename Name used to store the file
req.file.mimetype MIME type reported by the client
req.file.size Uploaded file size in bytes
req.file.path Storage path for a file saved on disk

You can use these properties to record file metadata in a database or display upload information to the user.

Remember that req.files is used for methods such as upload.array(). For upload.single(), Multer uses req.file instead.

Step 7: Upload Files from Multiple Form Fields

Sometimes a form needs different types of file inputs, such as profile pictures and identity documents.

In this situation, you can use upload.fields().

For example:


const uploadFields = upload.fields([
    { name: 'profileImage', maxCount: 1 },
    { name: 'documents', maxCount: 3 }
]);

app.post('/upload-profile', uploadFields, (req, res) => {
    const profileImage = req.files.profileImage || [];
    const documents = req.files.documents || [];

    res.send(`
        Profile images: ${profileImage.length}
Documents: ${documents.length} `); });

The corresponding form would contain inputs named profileImage and documents.


<form
    action="/upload-profile"
    method="POST"
    enctype="multipart/form-data"
>
    <label>Profile image:</label>
    <input type="file" name="profileImage">

    <label>Documents:</label>
    <input type="file" name="documents" multiple>

    <button type="submit">Upload</button>
</form>

With upload.fields(), req.files is an object whose properties correspond to the configured field names. Each property contains an array of uploaded files.

Use this approach when the application needs multiple file inputs with different limits.

Step 8: Run the Node.js Application

Open your terminal in the project directory and run:


node app.js

You should see the following message:


Server running at http://localhost:3000

Open this URL in your browser:


http://localhost:3000

Select up to five permitted files and click Upload Files.

If the upload succeeds, the application displays the number of files received and their generated filenames. The files are saved in the uploads directory.

Try uploading a file larger than the configured limit or a file with a disallowed type to test the validation and error-handling behavior.

Common Mistakes When Uploading Multiple Files

1. Forgetting the multiple Attribute

Without the multiple attribute, the user generally cannot select several files in the same file input.

Solution: Add multiple to the HTML file input.

2. Using Different Field Names

If the HTML form uses name=”files” but the server uses upload.array(‘images’, 5), Multer will reject the unexpected field.

Solution: Use matching field names in the form and backend.

3. Using req.file Instead of req.files

When using upload.array(), the uploaded files are stored in req.files, not req.file.

Solution: Use req.files to access the array of uploaded files.

4. Forgetting multipart/form-data

Multer expects a multipart request for normal HTML form file uploads.

Solution: Set enctype=”multipart/form-data” on the form.

5. Not Setting Upload Limits

Accepting unlimited files or very large uploads can consume disk space and server resources.

Solution: Configure file size and file count limits, and apply suitable request-rate limits.

6. Trusting the Original Filename

Client-supplied filenames can be misleading or contain unexpected characters.

Solution: Generate safe server-side filenames and store the original name separately only when it is needed.

Security Best Practices for Multiple File Uploads

When implementing file uploads in a real application, consider the following practices:

  • Validate file content: Do not rely solely on the extension or client-supplied MIME type.
  • Set file limits: Limit both individual file sizes and the number of files per request.
  • Generate unique filenames: Avoid filename collisions and unsafe storage paths.
  • Restrict allowed file types: Accept only formats required by the application.
  • Keep sensitive files private: Do not make private documents publicly accessible by default.
  • Use authentication and authorization: Restrict uploads to authorized users when necessary.
  • Scan files when appropriate: Use malware scanning for potentially dangerous documents.
  • Monitor storage usage: Prevent repeated uploads from exhausting available disk space.
  • Clean up failed or unwanted uploads: Define a retention and cleanup policy.
  • Consider cloud storage: For larger applications, object storage may be more suitable than local disk.

The example is intended for learning. A production system may require stronger content validation, malware scanning, access controls, monitoring, and other safeguards.

Conclusion

Multiple file upload is a useful feature in many Node.js applications. By combining Express.js and Multer, developers can receive several files in one request and save them to a configured storage location.

In this tutorial, you learned how to create a multiple-file upload form, configure Multer, use upload.array() and upload.fields(), access uploaded file details through req.files, and handle common upload errors.

Related Node.js Tutorials