Table of Contents

Introduction

File upload is the most basic operation for any application. Regarding Node, file upload with Multer in Node.js and Express is efficient and seamless. It is designed to simplify handling incoming files and efficiently store, receive, and upload it.

Today we will discuss and learn about file uploading in Nodejs Multer. Also, we will see how to upload images/videos using Multer in node js and express. Let’s begin our tutorial and learn about node js Multer file upload.

What is Multer in Nodejs?

Node js Multer is a middleware in node.js that handles multipart/form-data, which is principally used for uploading files. It is written on top of the busboy for maximum efficiency.

As a result, Multer makes the process of uploading files in Nodejs easier. It is an NPM package that tackles the complexities of file handling by integrating the middleware stack of Node applications.

Additionally, it allows renaming files, setting sizes, different types, and filtering files.

Steps-by-step tutorial of File Upload Using Multer in Node.js and Express

how to use multer in node js?
Following is the step-by-step guide to learning about how to upload Node Multer files.

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 if the destination is unavailable. 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 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. 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.

Copy Text
router.post('/uploadVideo', videoUpload.single('video'), (req, res) => {
   res.send(req.file)
}, (error, req, res, next) => {
    res.status(400).send({ error: error.message })
})

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 on how to upload files(Video/Image) using Node Multer 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 Node js Multer example.

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!

Want to Make a Straightforward Way to Handle File Uploads for your Node Applications?

Applying npm packages for efficiently handling file uploads in Node.js with Multer. Hire Node js developer to keep your app smooth and organized and avoid the most common pitfalls.

BOOK A FREE 30 MIN CALL TO KNOW HOW

Build Your Agile Team

Hire Skilled Developer From Us

Subscribe for
weekly updates

newsletter

What Makes Bacancy Stand Out?

  • Technical Subject Matter Experts
  • 2500+ Projects Completed
  • 90% Client Retention Ratio
  • 12+ Years of Experience

Our developers primarily focus on navigating client's requirements with precision. Besides, we develop and innovate to deliver only the best solutions to our clients.

get in touch
[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?