Welcome folks today in this blog post we will talk about how to make a image gallery in node.js express with the help of mongodb database and the mongoose library to connect to the mongodb database.The step by step youtube video is shown below just watch the video to follow with the blog. All the source code is given below copy and paste the code.
Requirements
1 |
npm i express |
Express will be the server on which the app will run on Port 5000
1 |
npm i multer |
Multer will be the library used for uploading the images on the server
1 |
npm i express-handlebars |
Express handlebars will be the template engine on which the app will run.
1 |
npm i mongoose |
Mongoose will be the library to connect with the database that will be used for the application
1 |
npm i --save-dev nodemon |
Nodemon will be a dev dependency which will automatically restart the application when we make any kinds of changes in the application.
Now Make a App.js file that will be the starting point of the application
1 2 3 4 5 6 7 8 9 10 11 12 |
const express = require("express"); const app = express(); app.get("/", (req, res) => { res.send("hello world") }); app.listen(5000, () => { console.log("App is listening on Port 5000"); }); |
So in this block of code we are initializing a express application and then starting a new app. When someone goes to the home route then we return hello world as a response. We start the application using the listen method at port 5000
Initializing the HandleBars Template Engine in App
In order to use handlebars into your application you first of all need to create a directory structure such as first of all you need to create views directory in that directory you need to create layout directory like this
main.handlebars file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!DOCTYPE html> <html> <head> <title>Image Gallery in Node.js Express Using Multer and MongoDB</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" /> </head> <body> {{{body}}} </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </html> |
home.handlebars
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<div class="container"> <br> <h1 class="text-center"> Image Gallery </h1> <br> <form action="/" method="POST" enctype="multipart/form-data"> <div class="form-group"> <label for="Select Image:">Select Image:</label> <input type="file" name="image" class="form-control" id=""> </div> <br> <div class="form-group"> <button class="btn btn-block btn-danger"> Upload Image </button> </div> </form> </div> |
Now Modify App.js to include the handlebars
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
const express = require("express"); var exphbs = require("express-handlebars"); const app = express(); app.engine("handlebars", exphbs()); app.set("view engine", "handlebars"); app.get("/", (req, res) => { res.render("home") }); app.listen(5000, () => { console.log("App is listening on Port 5000"); }); |
Now if you execute the app on command prompt you will see the following output
Multer Image Upload
Now in this section we will be uploading image files using multer so first of all you need to create the public directory inside the root project and inside it you need to create a directory named images to hold the uploaded images such as
1 |
app.use(express.static("public/images")); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
const multer = require("multer"); var Storage = multer.diskStorage({ destination: function (req, file, callback) { callback(null, "./public/images"); }, filename: function (req, file, callback) { callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname); }, }); var upload = multer({ storage: Storage, }).single("image"); //Field name and max count |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
app.post("/", (req, res) => { upload(req, res, function (err) { if (err) { console.log(err); return res.end("Something went wrong"); } else { console.log(req.file.path); var imageName = req.file.filename; res.render('home',success:true}) } }); }); |
In this section of code we have successfully completed the operation of uploading images to the images folder
1 2 3 4 5 6 |
{{#if success}} <div class="alert alert-success alert-dismissible"> <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> <strong>Success!</strong> Your Image File is Uploaded. </div> {{/if}} |
Handlebars code to show success message when image is uploaded
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const mongoose = require('mongoose') mongoose.connect('mongodb://localhost:27017/imagesDB',{useNewUrlParser:true,useUnifiedTopology:true}) var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { console.log("h"); }); var uploadSchema = new mongoose.Schema({ imagename:String }) var uploadModel = mongoose.model('image',uploadSchema) module.exports = uploadModel |
In this section of code we are connecting to mongodb and describing the schema of image file and exporting it.
Full Source Code
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 66 67 68 69 70 71 72 73 |
const express = require("express"); var exphbs = require("express-handlebars"); const multer = require("multer"); const imageModel = require("./models/upload"); const imageData = imageModel.find({}) const app = express(); app.engine("handlebars", exphbs()); app.set("view engine", "handlebars"); app.use(express.static("public/images")); var Storage = multer.diskStorage({ destination: function (req, file, callback) { callback(null, "./public/images"); }, filename: function (req, file, callback) { callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname); }, }); var upload = multer({ storage: Storage, }).single("image"); //Field name and max count app.get("/", (req, res) => { imageData.exec(function(err,data){ if(err) throw err; console.log(data) res.render('home',{records:data}) }) }); app.post("/", (req, res) => { upload(req, res, function (err) { if (err) { console.log(err); return res.end("Something went wrong"); } else { console.log(req.file.path); var imageName = req.file.filename; var imageDetails = new imageModel({ imagename: imageName, }); imageDetails.save(function (err, doc) { if (err) throw err; console.log("Image Saved"); imageData.exec(function(err,data){ if(err) throw err; res.render('home',{records:data,success:true}) }) }); } }); }); app.listen(5000, () => { console.log("App is listening on Port 5000"); }); |
DOWNLOAD SOURCE CODE