Upload Multiple Files Using Multer in Node.js and Express

Do you need to upload multiple files using multi in node.js and express? well, you have found the right tutorial. here you will learn to upload one or more files ( like jpg, png, gif, pdf, doc, text so on ) at a time with a complete source code.

There are many modules are available in npm to upload multiple files to the folder. But the Multer is the most popular & frequently used module in Node.js Express. So, you should use it.

Here is some useful reason to use Multer module –

  • Multer handles multipart/form-data for uploading multiple files.
  • Multer will not work without using enctype=”multipart/form-data”.
  • Even multer can easily upload multiple files at a tile

upload multiple files in node.js

Multiple Files Upload Using Multer

1. Install Express Application

Install Express Application and create the following folders & files to write a script for the multiple files upload.

nodeapp/
  |__controllers/
  |     |__upload-controller.js
  |__public/
  |     |__files/
  |__middlewares/
  |     |__upload-middleware.js
  |__routes/
  |     |__upload-route.js
  |__views/
  |     |__upload-form.ejs

2. Install Multer Module

You should install multer module with the help of the following command

nodeapp> npm install --save multer

3. Create Multiple Files Upload Form

You have to create multiple files upload form with the following attributes

  • method="POST" – To upload the file through the post method
  • enctype="multipart/form-data" –  to handle file uploading
  • name="files" – It is the name of the file input Field
  • Input file Field must have multiple attribute

File Name – upload-form.js

<!DOCTYPE html>
<html>
 <head></head>
 <body>
 <form action="/upload-files" method="POST" enctype="multipart/form-data">
     <label>Avatar</label>
     <input type="file"  name="files" multiple>
     <button type="submit">Upload</button>
</form>
 </body>
</html>

4. Upload Multiple Files to the Folder

Use the following points to upload multiple files to the folder  –

  • Create a folder middlewares
  • Also, create a file upload-middleware.js in the middlewares
  • Declare a folder path in the code cb(null, 'folder_path'). Here folder_path is declared as public/files

File Name – upload-middleware.js

var multer = require('multer');
module.exports.files={
    storage:function(){
        var storage = multer.diskStorage({
        destination: function (req, file, cb) {
          cb(null, 'public/files/')
        },
        filename: function (req, file, cb) {
            cb(null, file.originalname)
        }
      })
      
      return storage;
},
allowedFiles:function(req, file, cb) {
    // Accept images only
    if (!file.originalname.match(/\.(pdf|doc|txt|jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF)$/)) {
        req.fileValidationError = 'Only pdf|doc|txt|jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF file type are allowed!';
        return cb(new Error('Only pdf|doc|txt|jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF file type  are allowed!'), false);
    }
    cb(null, true);
}
}

 

5. Send Multiple Files Upload Request

  • You must include the Multer module require('multer')
  • Also, include a middleware file using require('../middlewares/upload-middleware')
  • Create a method uploadForm to display multiple files upload form through the GET request
  • Even create another method uploadFiles to send file upload request to the middleware through the POST request.

File Name – upload-controller.js

var multer  = require('multer');
var uploadMiddleware= require('../middlewares/upload-middleware');
module.exports={
    uploadForm:function(req,res){
        res.render('upload-form');
     },
     uploadFiles:function(req,res){
        var upload = multer({
                    storage: uploadMiddleware.files.storage(), 
                    allowedFiles:uploadMiddleware.files.allowedFiles 
                    }).single('files');
        upload(req, res, function (err) {
           if (err instanceof multer.MulterError) {
              res.send(err);
           } else if (err) {
              res.send(err);
           }else{
              res.render('upload-form');
           }
           
        })
        
     }
}

6. Create Routes to Upload Multiple Files

  • Include a controller file using require('../controllers/upload-controller')
  • Create a route /upload-files  with the GET method to display multiple files upload form
  • Also, Create another route /upload-files with the POST method to upload multiple files. This route will be called when you submit the form.

File Name – upload-route.js

const express = require('express');
const router = express.Router();
const uploadController= require('../controllers/upload-controller');
router.get('/upload-files',uploadController.uploadForm);
router.post('/upload-files',uploadController.uploadFiles);
module.exports = router;

7. Include the Router File in app.js

You must include the following lines of code in the app.js file

File Name – app.js

var uploadRouter = require('./routes/upload-route');
;
app.use('/', uploadRouter);

8. Run Node.js App to Upload Multiple Files

At last, upload  multiple files using the following URL

http://localhost:3000/upload-files

To upload multiple files, you have to work on the following steps –

  • Enter the above URL in your browser
  • Select multiple files from your local computer by pressing the ctrl/shift key
  • Click submit button

After that, all the files will be uploaded successfully.

9. My Suggestion

Dear developers, I hope you have understood the above script and you are able to upload multiple files in Node.js express using Multer. Now, you can easily implement other multiple files uploading in Node.js express.

If you have any doubts or questions. You can directly ask me through the below comment box.

 

Categories Node.js

2 thoughts on “Upload Multiple Files Using Multer in Node.js and Express”

Leave a Comment