In this node js tutorial, you will learn how to upload multiple images using multer in Node.js. In this tutorial, we will use the npm Multer you will see below. We are learning how to upload multiple images of Node js using multer, in express js Framework.

Image upload is a basic requirement of any project. So this example will guide you step by step how to upload multiple images using multer Express js Framework. And you can understand the concept of uploading multiple images easily to use.


Step 1 – Create Node JS App

In this step, open your terminal and execute the following command to create a node js app:

npm init -y


Step 2 – Install Express and Multer Dependencies

open again your command window and execute the following command to install express and multer dependencies:

npm install express multer --save


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


Step 4 – Create Server.js File

In this step, you need to create a server.js file and add the following code:

const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const port = 3000

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, 'uploads/');
    },
   
    filename: function(req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});
   
var upload = multer({ storage: storage })
   
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});
   
app.post('/', upload.array('multi-files'), (req, res) => {
  res.redirect('/');
});
   
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})


Step 5 – Create Form

In this step, create an index.html file to resize an image before upload in the node js app. So, add the following HTML code into it:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>How To Upload Multiple Image Using Multer In Node.js - phpcodingstuff.com</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <h1>How To Upload Multiple Image Using Multer In Node.js - phpcodingstuff.com</h1>
    <form action="/" enctype="multipart/form-data" method="post">
      <input type="file" name="multi-files" accept='image/*' multiple>
      <input type="submit" value="Upload">
    </form>  
  </body>
</html>


Step 6 – Run Development Server

You can use the following command to run the application server:


//run the below command
npm start
//after a run, this command open your browser and hit 
http://127.0.0.1:3000/

I hope it can help you...