Node.js Multer File Upload Type Validation Filters and Limit File Size and Error Handling Using Express Full Tutorial For Beginners With Examples

Node.js Multer File Upload Type Validation Filters and Limit File Size and Error Handling Using Express Full Tutorial For Beginners With Examples

 

Welcome folks today in this blog post we will be looking at multer file type validation file filters. In this post we will be validating the file uploads such as uploading images .jpg,.png for images and .mp4,.avi for videos. All the extensions of the files you can validate before actual uploads using multer validation filters.

 

 

 

Get Started

 

 

 

In order to get started we need to install the following dependencies

 

npm i multer

 

So you need to install this multer dependency to actually upload images

 

npm i express ejs nodemon

 

Three more dependencies such as express, ejs and nodemon. Just install it and you can see all your dependencies inside your package.json file.

 

Now you create a file called as index.js file and copy paste the following code

 

 

index.js

 

 

 

const express = require("express");

const app = express();

const multer = require("multer");

const path = require("path")

const PORT = process.env.PORT || 5000;

app.set("view engine", "ejs");


app.get("/", (req, res) => {
  res.render("index");
});

app.listen(PORT, () => {
  console.log(`App is listening on Port ${PORT}`);
});

 

 

You can see we have a simple express app listening on port 5000. So now you need to make the template index.ejs file and copy paste the following code

 

Now you need to create a folder called as views folder and inside it create a file called as index.ejs

 

 

views/index.ejs

 

 

 

<!DOCTYPE html>
<html>
  <head>
    <title>Multer File Upload Validation Example</title>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    />
  </head>
  <body>
      <div class="container">
          <h1 class="text-center">Multiple Form Fields Upload in Multer</h1>
          <form action="/uploadfile" method="post" enctype="multipart/form-data">
            <div class="form-group">
                <label for="file1">Upload File1:</label>
                <input type="file" name="file" required id="" class="form-control">
            </div>
            <div class="form-group">
                <button class="btn btn-danger btn-block">
                    Upload File
                </button>
            </div>
        </form>
      </div>
</body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  
</html>

 

 

 

Now we will make the post request to the route /uploadfile so we need to modify index.js file and copy paste the following code

 

 

app.post('/uploadfile',upload,(req,res) =>{
    if(req.files){
        console.log(req.files)
        console.log("files uploaded")
    }
})

 

 

So now we need to create a upload middleware function inside the post request that we have made to actually upload the files using multer. Inside this upload middleware function we need to first of all validate the files with file filters.

See also  Build a Wav File Sound or Voice Recorder Using Microphone in Browser Using HTML5 CSS3 & Javascript Full Project For Beginners

 

 

 

Multer File Validation with File Filters

 

 

Before validation, just make a public/uploads folders where we will storing the uploaded files. Just create it and after that just copy paste the following code in index.js file

 

 

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/uploads");
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + "-" + Date.now() + path.extname(file.originalname));
  },
});

 

 

So multer here using the diskstorage function to store the uploaded file. It takes two arguments such as destination where the file will be stored and secondly it takes the filename of the uploaded file.

 

 

var upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
      cb(null, true);
    } else {
      cb(null, false);
      return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
    }
  }
}).single('file');

 

 

So here in this block of code we are validating the image files extensions such as png,jpg,jpeg. If the uploaded files are only this extensions then only the files will upload.

 

fileFilter : fileFilter is the property available inside the multer where you can validate the input data inside the multer library.

 

cb: cb stands for callback function it will be automatically called whenever the validation fails and the error message will be returned by multer. That is only images files are supported.

 

 

 

Limit File Size in Multer

 

 

 

Now inside the multer library we will be limiting the file size to be uploaded inside our application. Multer supports a special property called as limits . Inside this object there is a  property called as fileSize which will have the maximum size of the uploaded file

 

 

var upload = multer({
  storage: storage,
  limits: { fileSize: maxSize }
}).single('file');

 

See also  Node.js Express Text Splitter By Space,Comma and Semicolon Online Tool Made in Javascript Using Split Method 2020

 

 

So now we just need to modify index.js file and copy paste the following code to it

 

 

const maxSize = 1 * 1024 * 1024; // for 1MB

var upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    if (
      file.mimetype == "image/png" ||
      file.mimetype == "image/jpg" ||
      file.mimetype == "image/jpeg"
    ) {
      cb(null, true);
    } else {
      cb(null, false);
      return cb(new Error("Only .png, .jpg and .jpeg format allowed!"));
    }
  },
  limits: { fileSize: maxSize },
}).single('file');

 

 

 

 

Multer Error Handling in Uploading Files

 

 

Now we will be handling the errors while uploading files using multer. So add some code to your index.js file and copy paste the following code

 

 

app.post("/uploadfile",(req, res) => {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.
      res.send(err)
    } else if (err) {
      // An unknown error occurred when uploading.
      res.send(err)
    }
 
    // Everything went fine.
  })
});

 

 

 

 

Full Example Source Code

 

 

 

So now inside your index.js file and copy paste the following code. This will be a complete example in which we will be uploading files along side with file filter validation and limit file size as well.

 

 

 

const express = require("express");

const app = express();

const multer = require("multer");

const path = require("path");

const PORT = process.env.PORT || 5000;

app.set("view engine", "ejs");

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/uploads");
  },
  filename: function (req, file, cb) {
    cb(
      null,
      file.fieldname + "-" + Date.now() + path.extname(file.originalname)
    );
  },
});
const maxSize = 1 * 1024 * 1024; // for 1MB

var upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    if (
      file.mimetype == "image/png" ||
      file.mimetype == "image/jpg" ||
      file.mimetype == "image/jpeg"
    ) {
      cb(null, true);
    } else {
      cb(null, false);
      return cb(new Error("Only .png, .jpg and .jpeg format allowed!"));
    }
  },
  limits: { fileSize: maxSize },
}).single('file');

app.post("/uploadfile",(req, res) => {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.
      res.send(err)
    } else if (err) {
      // An unknown error occurred when uploading.
      res.send(err)
    }
   
    console.log(req.file)
 
    // Everything went fine.
  })
});

app.get("/", (req, res) => {
  res.render("index");
});

app.listen(PORT, () => {
  console.log(`App is listening on Port ${PORT}`);
});

 

See also  Node.js Express Project to Convert Image to Byte Array in Browser Using Javascript Full Project For Beginners

 

 

When you execute this node.js script by running the command such as

 

node index.js

 

You will see the following screenshot

 

 

 

 

 

 

 

 

 

 

Leave a Reply