Open In App

How to add authentication in file uploads using Node.js ?

Last Updated : 14 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

There are multiple ways to upload files and apply authentications to them. The easiest way to do so is to use a node module called multer.   We can add authentication by restricting users on file uploads such as they can upload only pdf and the file size should be less than 1 Mb. 

There are many modules available in the market but multer is the most popular. It provides us with different options to customize and restrict which type of file formats we want.

Prerequisites: You should know how file uploading in multer works.

Installation of multer module:

Step 1: You can the multer by running the below command

npm i multer

Step 2: You can check the module version by running the below command.

npm version multer

Step 3: After that, you can just create a folder and add a file and run the created file by the below command.

node <filename>.js

Step 4: Requiring module: You need to include the multer module in your file by using these lines.

const multer = require('multer');

1. Restricting the user by fileSize:

Example: Multer provides us with a property called limits in which we can define the file size and 

Javascript




// Requiring the multer module in our project
const multer = require('multer');
const upload = multer({
    dest: 'src',
    limits: {
  
        // Here we have to give size in bytes 
        fileSize: 1000000;
    }
})


Output:

In the above code, we are restricting the user by specifying that the program will only take files which has a size less than or equal to the specified size.

In the above image, we are trying to upload an image that is greater than 1 MB so it is giving us an error.

2. Restricting by fileType

Example: The multer has a function called fileFilter which gives us access to file objects and then we can perform necessary operations in it.

Javascript




// Requiring the multer module in our project
const multer = require('multer');
const upload = multer({
  
    // dest is the destination where file will be stored
    dest: 'src',
    fileFilter(req, file, cb) {
  
        // We are providing a regular expression 
        // which accepts only jpg,jpeg and png
        if (!file.originalname.match(/\.(png|jpg|jpeg)$/)) {
            return cb(new Error('Upload an image'));
        }
        cb(undefined, true);
    }
})


Output:

In the above example, we are uploading a doc file but the multer is not accepting it as we are only accepting images.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads