,

Upload Multiple Files Easily Using Multer in Node.js and Express.js

Posted by

Easily File Upload Using Multer in Node.js and Express.js (Part 2 || multiple file)

Easily File Upload Using Multer in Node.js and Express.js (Part 2 || multiple file)

In the first part of this tutorial, we covered how to use Multer to easily handle file uploads in Node.js and Express.js. In this part, we will extend the functionality to allow for the upload of multiple files.

Setting up the Project

If you haven’t already set up a Node.js and Express.js project with Multer, please refer to the first part of this tutorial. Once you have the project set up, we can start adding the functionality for multiple file uploads.

Modifying the Routes

In your Express.js routes, you can modify the file upload endpoint to accept multiple files. You can do this by specifying the field as an array in the Multer middleware configuration.

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

const app = express();

app.post('/upload', upload.array('files', 5), (req, res) => {
  // Handle the file uploads
});
    
  

In this example, we have specified `upload.array(‘files’, 5)` to allow for multiple files to be uploaded with the field name `files` and a limit of 5 files. You can adjust the field name and limit as per your requirements.

Modifying the HTML Form

In your HTML form, you can modify the file input to accept multiple files by adding the `multiple` attribute.

    

  
  

    
  

With the `multiple` attribute, users can select multiple files to upload at once.

Handling Multiple File Uploads

In your route handler, you can handle the multiple file uploads by accessing `req.files` which will be an array of files. You can then process each file as needed.

    
app.post('/upload', upload.array('files', 5), (req, res) => {
  // Handle the file uploads
  if (req.files) {
    req.files.forEach(file => {
      // Process each file
    });
  }
});
    
  

With these changes, you can easily allow for the upload of multiple files in your Node.js and Express.js project using Multer.

That’s it! You have successfully extended the functionality to handle multiple file uploads using Multer in Node.js and Express.js.