Category: Express API

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,

Using Express router with Node JS

Hello People. This article is about using Express router with Node JS. Express Router is a built-in class that refers to how an application’s endpoints (URIs) respond to client requests. The express router class helps in the creation of route handlers.

Routing is defined using methods of the Express app object that correspond to HTTP methods; for example, app.get() to handle GET requests and app.post to handle POST requests.  For a full list, see the app.METHOD.

App.all() is used to handle all HTTP methods and app.use() to specify middleware as the callback function (See Using middleware for details).

These routing methods specify the callback function (sometimes called “handler functions”) called when the application receives a request to the specified route (endpoint) and HTTP method.

In other words, the application “listens” for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.

Routing methods can have more than one callback function as arguments.

With multiple callback functions, it is important to provide next as an argument to the callback function and then call next() within the body of the function to hand off control to the next callback.

Using Express router with Node JS

See an example of basic routing here.

// server.js

const express = require('express')
const app = express()

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
  res.send('hello world')
})

Now, let’s head back to our demo project.

Step 1: Create an express project.

Create one project folder and go inside that folder.

mkdir erouter && cd erouter

Now, initialize the package.json file using the following command.

npm init -y

Now, install the express using the following command.

npm install express --save

# or

yarn add express

Step 2: Let us write the first express route.

Now, inside the root folder. Create one file called server.js and add the following code.

// server.js

const express = require("express");
const app = express();
const PORT = process.env.PORT = 3000;

let router = express.Router();

router.get('/',function(req,res){
  res.json({'message' : 'Ping Successfull'});
});

app.use('/api',router);

app.listen(PORT,function(){
  console.log('Server is running at PORT:',PORT);
});

First, we have imported all the required modules and then create an object of a router, and then defined the root route. Then we have used the middleware saying that if any request comes with the ‘/api’, it will call the router function with its route. So in our case, we will get a JSON response.

So this was the example of basic routing that we used to do when creating a web application with express on the Node.js platform.

Express router methods

Express supports the main following routing methods.

  1. GET
  2. POST
  3. PUT
  4. HEAD
  5. DELETE
  6. OPTIONS

There are still other methods, but mainly we used the above methods in a web application. In addition, there is a routing method called app.all(), which is not derived from any HTTP method.

The routing method gets loaded for functions at a specified path for all of the request methods.

Route Paths

The route path is used to define an endpoint where requests can be made. It is like a backend endpoint.  In the Express, route paths can be string patterns or regular expressions.

In the above example, the route path is below.

// server.js

router.get('/',function(req,res){
  res.json({'message' : 'Ping Successfull'});
});

Here, the router path is “/.”

Route Parameters

The route parameters are used to capture the values specified to a particular position in the URL. Thus, they are called URL segments.

The values obtained are made available in a req.params object, using the name of the route parameter specified in the path as the keys of the values.

Route parameter is significant in functionality like edit, update, and delete. Therefore, we generally pass the ID on the parameter and extract it from the request. The syntax is like this.

http://localhost:3000/api/user/:id

Now, at Express Router, we can access the ID using the following code.

http://localhost:3000/api/user/1

In the req.params, the following will be available: { “id”: “1” }

So, we can access the 1 using the following code.

req.params.id

Express Router POST Request

The basic syntax of the express post route is the following.

// server.js

router.post('/', function(req, res){
   res.send('It's a post route, grab the data and save in the Mongo');
});

Inside the router post method, we save the data from the req and extract that data from the req and save the data inside the database.

Just like the following code.

router.route('/store').post(function (req, res) {
  let model = new Model(req.body);
  model.save()
    .then(game => {
    res.status(200).json({'model': 'Your data is saved'});
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});

So, here we have used the Mongoose model to save the data in the MongoDB database. It is just a real-time example that will show you how to create your post request and save the data in the database.

Router-level middleware

Router-level middleware works the same way as application-level middleware, except it is bound to an instance of express.Router().

// server.js

const app = express();
const router = express.Router();

router.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});

router.use('/user/:id', function (req, res, next) {
  console.log('Request URL:', req.originalUrl);
  next();
}, function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});

Hope this article on Using Express router with Node JS is useful to you. To read about styled components, please visit How to use styled components in react native

Navigation

× Contact Us