Welcome folks today in this blog post we will be looking on how to validate file uploads
in node.js and express using the multer
library using different file filters
and errors. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new node.js
project using the below command as shown below
npm init -y
After that you need to install the below libraries using the npm
command as shown below
npm i express
npm i multer
After that you need to make the uploads
directory where you will see storing all the uploaded
files. And after that you need to make the index.js
file and copy paste the following code
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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}`); }); |
As you can see we are loading the index.ejs
template of ejs when we go to the /
home route.
Now we need to create the views
directory and inside it create the index.ejs
file and copy paste the following code
views/index.ejs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<!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> |
As you can see we have the simple input
field where we allow the user to select the file
to upload and then we are making the post
request to the /uploadfile
route to actually upload
the file.
Now inside the index.js
we need to initialize the multer
library with different validations
and error handling
to allow users to upload the file as shown below
index.js
1 2 3 4 5 6 7 8 9 10 |
let multer = require('multer') var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "uploads"); }, filename: function (req, file, cb) { cb(null, file.fieldname + "-" + Date.now() + path.extname(file.originalname)); }, }); |
As you can see we are using the diskStorage
approach to save files
using multer. And here we are storing it inside the uploads
directory.
1 2 3 4 5 6 7 8 9 10 11 |
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'); |
As you can see we are passing the fileFilter
validation rule to only allow the image
file extensions to be accepted at the time of upload
here we are allowing the png,jpg
files only. And also we are showing the error to the user that only jpg and png
supported
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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'); |
And now we have declared the variable
for storing the maxSize
for uploaded file. And inside multer we have the property called limits
which allow the user to specify the maximum size of the uploaded
file.
FULL SOURCE CODE
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
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}`); }); |