Easily File Upload Using Multer in Node.js and Express.js

Introduction

File upload is the most basic operation for any application. Combining Node.js with Express and the Multer library, we can smoothly implement the file upload with multer in node.js and express. Today we are going to discuss and learn about file upload using multer in node js and express, also we will see how to upload image/video using multer in node js and express. Let’s begin our tutorial and learn about file upload using Multer in NodeJS and Express.js.

What is Multer?

According to the documentation-
Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of the busboy for maximum efficiency.

Click here to explore more regarding the implementation of Multer.

Steps File Upload Using Multer in Node.js and Express

how to use multer in node js?
Follow the step-by-step guide to learn about how to upload file using multer in node js and express.

Initial Setup

Create a directory

Copy Text

mkdir MulterApp
cd MulterApp

Define package.json file

For creating one, run this command:

Copy Text

npm init

Install dependencies

We only have two dependencies to be installed- Express and Multer. So here are the commands

To install Express-

Copy Text

npm install express --save

To install Multer-

how to install multer in node js?

Copy Text

npm install --save multer

Now, it’s time to code.

First of all, create a file and name it anything; here it is app.js. I’ll be coding the entire code in app.js to keep it simple for you. Further, loading the express module with the help of require() and then, at last, writing the below-mentioned code for setting up the basic express server.

//app.js

Copy Text

const express = require('express');
const path = require('path');
const app = express()
const port = process.env.PORT || 3000
app.get(‘/’, (req, res) => { 
    res.send(‘Hello People’); 
});
app.listen(port, () => {
    console.log('Server is up on port ' + port);
})

Run this command to verify-

Copy Text

node app.js

Hit http://localhost:3000, and you should see “Hello People” in your window.

hello people

Adding Multer

For simplicity purpose, I’ll store all the uploaded files in the local folder. Write the below-mentioned code for loading multer in our app.js file

Copy Text

const multer = require(‘multer’);

Multer Storage for Single Image Upload

Now, the next thing to be implemented is to define a storage location for all the files. Multer made it easy by providing an option to store our files to disk. We will set up a directory to save all the files and provide them a new identifier.

Create a folder- images, in the root directory.

// Image Upload

Copy Text

const imageStorage = multer.diskStorage({
    // Destination to store image     
    destination: 'images', 
      filename: (req, file, cb) => {
          cb(null, file.fieldname + '_' + Date.now() 
             + path.extname(file.originalname))
            // file.fieldname is name of the field (image)
            // path.extname get the uploaded file extension
    }
});

1. Destination: Destination is used so that the application can know where to store images. It can be a string (e.g. ‘./upload’). The default directory for all the temporary files is used in case the destination is not provided. Creating a directory is compulsory when you use the destination as a function. Or else, if you use destination as string, Multer will create directory.

2. Filename: Filename determines what a file should be named in the folder.

A random file name with no extension will be given if you don’t provide the file’s name. The function takes three parameters – the request object, the file object, and a callback function. The two arguments to the callback are:

  • null: as we aren’t showing an error.
  • file.originalname – in this demo, I have used the same file name as they are uploaded. You can choose any name.

We have used the multer() method in the below-mentioned snippet-

Copy Text

const imageUpload = multer({
      storage: imageStorage,
      limits: {
        fileSize: 1000000 // 1000000 Bytes = 1 MB
      },
      fileFilter(req, file, cb) {
        if (!file.originalname.match(/\.(png|jpg)$/)) { 
           // upload only png and jpg format
           return cb(new Error('Please upload a Image'))
         }
       cb(undefined, true)
    }
}) 

1. The multer() method takes an object with storage property.
2. The limits property describes the maximum size of the file.

The fileFilter() method is for security reasons. I have validated files before it is uploaded to the servers. Here, it will accept only two extensions – .png and .jpg. After this, it’s time to create the post route. We will make a POST request to localhost:3000/uploadImage.

Add the following code in the app.js-

Copy Text

// For Single image upload
router.post('/uploadImage', imageUpload.single('image'), (req, res) => {
     res.send(req.file)
}, (error, req, res, next) => {
     res.status(400).send({ error: error.message })
})

I have used imageUpload.single(‘image’) for uploading a single file. As mentioned earlier, the multer adds a file object to the request. The file object has metadata of the file. Here inside the single() method, we have passed the field name. The same field name we will pass in Postman.

To test the endpoint, open Postman.

Keep key name or the field name same as those given in the imageUpload.single() Check the image in the Images folder.

Upload Multiple Images using Multer in Node JS

Now we will upload multiple files using Multer. For that, multer provides another function named arrays(fieldname[, max_count]) that takes an array of files, all with the name fieldname. It will generate an error in case you upload more than max_count files. The array of files will be saved in req.files.

Here no need to create any storage. We will use the same storage as before.

Copy Text

// For multiple image upload

router.post('/uploadBulkImage', imageUpload.array('images', 4),     (req, res) => {
   res.send(req.files)
}, (error, req, res, next) => {
    res.status(400).send({ error: error.message })
})

Open Postman, enter the URL, select multiple files and click Send.

Verify the image in the Images folder.

Upload Video Files using Multer

Let’s further learn about video file upload in node js using multer and video file upload in express using multer. As discussed above, we have to create diskStorage to upload the video. And for that, use the below-mentioned snippet-

// Video Upload

Copy Text

const videoStorage = multer.diskStorage({
     destination: 'videos', // Destination to store video 
     filename: (req, file, cb) => {
         cb(null, file.fieldname + '_' + Date.now() 
          + path.extname(file.originalname))
     }
});

Use multer() method to upload video the way we did for images.

Copy Text

const videoUpload = multer({
     storage: videoStorage,
     limits: {
     fileSize: 10000000 // 10000000 Bytes = 10 MB
     },
     fileFilter(req, file, cb) {
       // upload only mp4 and mkv format
       if (!file.originalname.match(/\.(mp4|MPEG-4|mkv)$/)) { 
          return cb(new Error('Please upload a video'))
       }
       cb(undefined, true)
    }
})

After this, create a POST request to upload the video.

Test the API in Postman as explained above.

Check the video in the videos folder.

You can find the source code here – Github Repository

Our clients say Bacancy provides the best and highly-skilled developers!
Want the best? Get the best! Contact Bacancy and hire Node.js developer for your dream projects!

Conclusion

I hope you found this tutorial of how to upload files(Video/Image) using multer in node js and express.js helpful and have learned about image and video file upload using Multer in NodeJs and Express.js. File upload can be an exciting feature, but its implementation doesn’t have to be difficult always. We can handle multipart/form-data at our ease, using Multer and Express.js.

If you are looking for file upload in node js using multer and file upload in Express.js using multer, then you have landed on the right page. At Bacancy Technology, we hold a pool of skilled Node.js developers whose expertise can be leveraged for handling multipart and form-data. Hire Nodejs developer from us to integrate file upload in node js using multer in any application. Build your next-gen application with your choice of frontend and integrate the file uploads based on the knowledge acquired from Nodejs tutorials.

Keep Learning and Coding!