Category: multer

How to upload multiple files using multer

Hello People. This article is about how to upload multiple files using multer.  You can use Multer because it is the most popular module in Node.js Express. 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 time. So, let us see how to use multer to upload multiple files.

Install Express Application

Install Express Application and you can use the following file structure.

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

Install Multer Module

You should install multer module.  Use command npm install –save multer

Create an 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
<!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>
How to upload multiple files using multer

Let us not delay and see how to do this.

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
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);
}
}

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.
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');
           }
           
        })
        
     }
}

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.
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;

Include the Router File in app.js

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

File Name – app.jsvar uploadRouter = require(‘./routes/upload-route’);;app.use(‘/’, uploadRouter);

Run Node.js App to Upload Multiple Files

At last, upload  multiple files using the following URLhttp://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.

Hope this article on how to upload multiple files using multer is useful to you and please visit Using Express router with Node JS to read about express router,

Navigation

× Contact Us