How to add authentication in file uploads using Node.js ?
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.
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
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.
In the above example, we are uploading a doc file but the multer is not accepting it as we are only accepting images.
Please Login to comment...