How to Upload Multiple Files in Multiple Form Fields in Node.js and Express Using Multer Library Full Example For Beginners

How to Upload Multiple Files in Multiple Form Fields in Node.js and Express Using Multer Library Full Example For Beginners

 

 

 

Welcome folks today in this blog post we will be looking on how to upload multiple files present in multiple form fields in node.js and express using the multer library. All the source code of the example will be shown below.

 

 

Get Started

 

 

In order to get started you need to install node.js on your computer and then execute the below commands to get started with the node.js and express project

 

npm init -y

 

npm i express

 

npm i ejs

 

npm i multer

 

npm i nodemon

 

 

Express will be the main node.js server which will be running the main application

 

ejs It is the template engine which express uses to render out html documents in express

 

multer It is the actual file upload library which is used to upload files

 

nodemon It is a special dependency which automatically restarts the application for you when you make any changes to it.

 

Now after installing all these dependencies a package.json file will be created in the root folder. Now you just need to make a index.js file in the root folder which will be the starting point of the application

 

index.js

 

 

const express = require('express')

const app = express()

const PORT = process.env.PORT || 5000

app.set("view engine","ejs")

app.get('/',(req,res) => {
    res.render("index")
})



app.listen(PORT,() => {
    console.log(`App is listening on Port ${PORT}`)
})

 

 

 

Now here in this block of code we are loading the required dependencies which are express and ejs template engine and we are starting the application at port 5000

 

Now we are loading a template index.ejs so for that you need to create this template in the views folder.

Now create a views folder in the root folder like this views/index.ejs and create a file called as index.ejs

 

index.ejs

 

 

<!DOCTYPE html>
<html>
  <head>
    <title>Currency Converter in Javascript</title>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    />
  </head>
  <body>
      <div class="container">
          <h1 class="text-center">Multer Multiple Field File Upload Example</h1>
          <form action="/uploadfile" id="post" method="post" enctype="multipart/form-data">
            <div class="form-group">
              <label for="file1">Upload File 1:</label>
              <input type="file" name="file1" id="" required class="form-control">
            </div>
            <div class="form-group">
                <label for="file2">Upload File 2:</label>
                <input type="file" name="file2" id="" required class="form-control">
              </div>
              <div class="form-group">
                  <button class="btn btn-danger btn-block">
                      Upload Files
                  </button>
              </div>
        </form>
      </div>
</body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</html>

 

READ  How to Play Audio in Browser After Few Seconds Delay Using Settimeout() Method in Javascript Full Project For Beginners

 

 

Now when you launch your node.js app by running

 

node index.js

 

you will see this screenshot

 

 

 

 

Now you can see here we have multiple file input fields we need to take the input from the user and upload these files to the express server. For storing it we need some folders that we need to create right now.

 

Now go to the root folder create a public/uploads directories or folder and here we will be storing files which will be uploaded.

 

 

 

Storing Files in Multer

 

 

Now we will write some server side code to actually store the files which are coming from the client side. So multer supports different options to store the files we will actually use the simplest one

which is disk storage approach

 

 

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
  }
})
 
var upload = multer({ storage: storage })

 

 

 

Here in this snippet of code multer is taking use of diskStorage Method inside which we are passing two arguments first argument is destination. Destination is actually where you need to store the file. So here we are providing the actual path you can see cb function second argument is the path. Here you will write public/uploads and then we have the second argument which is the actual filename which will be given to the uploaded file by multer. So here you can attach a random name or any sort of name that you want. Here we are providing a random name with the help of Date function.

 

And lastly you can see we are calling the multer constructor function passing the option which is storage to the actual storage object which we have defined earlier on.

So now we need to add some code to our index.js file and update the code like this

 

const express = require("express");

const app = express();

const multer = require("multer");

const PORT = process.env.PORT || 5000;

const path = require('path')

app.set("view engine", "ejs");

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/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.render("index");
});

app.listen(PORT, () => {
  console.log(`App is listening on Port ${PORT}`);
});

 

READ  Build a Website URL Bookmarker CRUD Application in Javascript Full Project For Beginners

 

 

So now we need to distinguish which form field we are processing in multer so for doing this we have a special fields function in multer.

 

 

var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])

 

 

You can see in this block of code we are attaching multiple file input fields inside multer upload function passing array of objects. The first object is equal to the first input field values which include the name of the input field and the maximum no of files allowed to upload.

 

So in this manner we need to replace the name parameter to the actual names that we have given in the index.ejs

 

Going back to index.js file make this modifications and copy paste the code

 

 

const express = require("express");

const app = express();

const multer = require("multer");

const path = require("path")

const PORT = process.env.PORT || 5000;

app.set("view engine", "ejs");

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/uploads");
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + "-" + Date.now() + path.extname(file.originalname));
  },
});

var upload = multer({ storage: storage });

var uploadMultiple = upload.fields([{ name: 'file1', maxCount: 10 }, { name: 'file2', maxCount: 10 }])


app.get("/", (req, res) => {
  res.render("index");
});

app.listen(PORT, () => {
  console.log(`App is listening on Port ${PORT}`);
});

 

 

You need to replace it with your name parameters as shown below.

 

 

 

 

So now after replacing it we need to modify the index.js file and copy paste the below code

 

const express = require("express");

const app = express();

const multer = require("multer");

const path = require('path')

const PORT = process.env.PORT || 5000;

app.set("view engine", "ejs");

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/uploads");
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + "-" + Date.now() + path.extname(file.originalname));
  },
});

var upload = multer({ storage: storage });

var uploadMultiple = upload.fields([{ name: 'file1', maxCount: 10 }, { name: 'file2', maxCount: 10 }])


app.get("/", (req, res) => {
  res.render("index");
});

app.post('/uploadfile', uploadMultiple, function (req, res, next) {

    if(req.files){
        console.log(req.files)

        console.log("files uploaded")
    }
    
})

app.listen(PORT, () => {
  console.log(`App is listening on Port ${PORT}`);
});

 

 

So now as you can see inside this we are making a post request to the /uploadfile route and passing the middleware function which we have created uploadMultiple we are passing it in the route also. After uploading the files it will return true and prints it in the console that files uploaded. As you can see in the below figure.

READ  What is the Difference Between Node and Nodemon

 

 

 

Leave a Reply