Welcome folks today in this blog post we will be uploading image to mysql database using fileupload library in node.js and express and display it using ejs in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to initialize a new node.js
project using the below command as shown below
npm init -y
npm i express
npm i mysql
npm i express-fileupload
npm i ejs
After that you need to create the mysql
database and also we need to create the table
as shown below in xampp control panel
Now you need to make the index.js
file and copy paste the below 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 |
var express = require("express"), routes = require("./routes"), path = require("path"), fileUpload = require("express-fileupload"), app = express(), mysql = require("mysql"), bodyParser = require("body-parser"); var connection = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "sampledb", }); connection.connect(); global.db = connection; // all environments app.set("port", process.env.PORT || 8080); app.set("views", __dirname + "/views"); app.set("view engine", "ejs"); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(express.static(path.join(__dirname, "public"))); app.use(fileUpload()); // development only app.get("/", routes.index); //call for main index page app.post("/", routes.index); //call for signup post app.get("/profile/:id", routes.profile); //Middleware app.listen(8080); |
As you can see in the above code we are importing the required libraries which is express, and express-fileupload library. And also we are setting the view engine which is ejs
and for that we need to create the views
directory inside the nodejs project here we will store all the ejs
template files. And also we are connecting to the mysql database which is sampledb
we are using the mysql module for this. For this we are using the createConnection()
method to connect to the mysql database using the username,password and localhost. And then we are storing that database connection variable inside global variable. And after that we are making the different routes for this project. We are importing the routes.js file at the very top. And then we are mapping the methods defined inside the routes.js
file to different routes. And then we are starting the express app at port 8080.
Directory Structure of Node.js Express App
And now we need to make the public
folder and inside that we need to make the images
folder and inside it we need to make the uploaded_images
folder as shown above. And also we need to make the views
folder also to store the ejs templates.
And now guys we will now define the routes.js
file where we will define all the methods for the application as shown below
routes.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 |
exports.index = function(req, res){ message = ''; if(req.method == "POST"){ var post = req.body; var name= post.user_name; var pass= post.password; var fname= post.first_name; var lname= post.last_name; var mob= post.mob_no; if (!req.files) return res.status(400).send('No files were uploaded.'); var file = req.files.uploaded_image; var img_name=file.name; if(file.mimetype == "image/jpeg" ||file.mimetype == "image/png"||file.mimetype == "image/gif" ){ file.mv('public/images/uploaded_images/'+file.name, function(err) { if (err) return res.status(500).send(err); var sql = "INSERT INTO `users_image`(`first_name`,`last_name`,`mob_no`,`user_name`, `password` ,`image`) VALUES ('" + fname + "','" + lname + "','" + mob + "','" + name + "','" + pass + "','" + img_name + "')"; var query = db.query(sql, function(err, result) { res.redirect('profile/'+result.insertId); }); }); } else { message = "This format is not allowed , please upload file with '.png','.gif','.jpg'"; res.render('index.ejs',{message: message}); } } else { res.render('index'); } }; |
And also you can see in the above code we are writing the index
method whenever you hit the home route. Here we are checking which method is there either get or post. If the method is get then we are showing the template
which is stored inside the views folder which is index.ejs
. This contains the simple user registration form where the user can enter the information such as firstname,lastname,mobileno and also upload the profile image and also enter the username and password as shown below
For this we need to make the index.ejs
file inside the views folder as shown below
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 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 74 75 |
<!DOCTYPE html> <html> <head> <title>Currency Converter in Javascript</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" /> </head> <body> <div class="container col-sm-12" id="mainform"> <div id="signupbox" style=" margin-top:50px" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2"> <div class="panel panel-info"> <div class="panel-heading"> <div class="panel-title">Register</div> </div> <div class="panel-body" > <form class="form-horizontal" role="form" method="post" action="/" enctype="multipart/form-data"> <% if (message.length > 0) { %> <div class="alert alert-success col-sm-12"><%= message %></div> <% } %> <div id="signupalert" style="display:none" class="alert alert-danger"> <p>Error:</p> <span></span> </div> <div class="form-group"> <label for="first_name" class="col-md-3 control-label">First Name</label> <div class="col-md-9"> <input type="text" class="form-control" name="first_name" placeholder="First Name"> </div> </div> <div class="form-group"> <label for="last_name" class="col-md-3 control-label">Last Name</label> <div class="col-md-9"> <input type="text" class="form-control" name="last_name" placeholder="Last Name"> </div> </div> <div class="form-group"> <label for="mob_no" class="col-md-3 control-label">Mobile Number</label> <div class="col-md-9"> <input type="number" class="form-control" name="mob_no" placeholder="Mobile Number"> </div> </div> <div class="form-group"> <label for="mob_no" class="col-md-3 control-label">Profile Image</label> <div class="col-sm-9"> <input class="form-control" type="file" name="uploaded_image" accept=""/> </div> </div> <div class="form-group"> <label for="user_name" class="col-md-3 control-label">User Name</label> <div class="col-md-9"> <input type="text" class="form-control" name="user_name" placeholder="User Name"> </div> </div> <div class="form-group"> <label for="password" class="col-md-3 control-label">Password</label> <div class="col-md-9"> <input type="password" class="form-control" name="password" placeholder="Password"> </div> </div> <div class="form-group"> <!-- Button --> <div class="col-md-offset-3 col-md-9"> <button id="btn-signup" type="submit" class="btn btn-info"><i class="icon-hand-right"></i>   Register</button> </div> </div> </form> </div> </div> </div> </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 different html5 form input fields where the user can enter the information as shown below
And now if the user enter all the information inside the html5 form if we hit the register button then we will insert this information to the mysql database.
As you can see if the request method is post. Then we will get the user submitted information and we will insert the information inside the mysql database. And also we are using the mv()
function to move the uploaded image by the user to the public/images/uploaded_images folder as shown below. Now you will see after submitting the form you will see the image there in uploaded_images and you will see the information there in mysql table
Making the Profile Page
Now guys we will now write the function of profile inside the routes.js
file as shown below
routes.js
1 2 3 4 5 6 7 8 9 10 11 |
exports.profile = function(req, res){ var message = ''; var id = req.params.id; var sql="SELECT * FROM `users_image` WHERE `id`='"+id+"'"; db.query(sql, function(err, result){ if(result.length <= 0) message = "Profile not found!"; res.render('profile.ejs',{data:result, message: message}); }); }; |
As you can see in the above code we are first of all getting the id
of the user. Based upon the id we are fetching the profile of the user. Here we are using the select statement and we are fetching all the data from the users_image
table where id is equal to the id passed inside this method. And after that we are passing the information to the profile.ejs
template. And we are passing the data
to the template and also passing the message as well. If profile is not found
Now we need to make the profile.ejs
file and copy paste the below code
views/profile.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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<!DOCTYPE html> <html> <head> <title>Currency Converter in Javascript</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" /> </head> <body> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 col-xs-offset-0 col-sm-offset-0 col-md-offset-3 col-lg-offset-3 toppad" style="padding-top:30px"> <% if (message.length > 0) { %> <div class="alert alert-danger col-sm-12" ><%= message %></div> <% } else {%> <div class="panel panel-info"> <div class="panel-heading"> <h3 class="panel-title"><%=data[0].first_name%>, <%=data[0].last_name%></h3> </div> <div class="panel-body"> <div class="row"> <div class="col-md-3 col-lg-3 " align="center"> <img width="100" height="100" alt="User Pic" src="http://localhost:8080/images/uploaded_images/<%=data[0].image%>" class="img-circle img-responsive"> </div> <div class=" col-md-9 col-lg-9 "> <table class="table table-user-information"> <tbody> <tr> <td>User Name:</td> <td><%=data[0].user_name%></td> </tr> <tr> <td>Mobile:</td> <td><%=data[0].mob_no%></td> </tr> </tbody> </table> </div> </div> </div> </div> <% } %> </div> </div> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </html> |
And now if you go to the browser and then type the url http://localhost:8080/profile/3
and here as you can see we are passing the id
of the user which is 3 then it will show the information as shown below
Get Full Source Code