If you really want to learn how to display an image from MySQL database in Node.js then you are reading the right tutorial. Here, you will learn it with Model, View & controller that will be very easy to understand.
If you are a web developer then you definitely need to show images on the web page dynamically. Once you learn it, you will easily display dynamic images in the gallery, profile, cover & other sections where you need them.
Fetch/Retrieve image from database in node.js & Express
Before displaying images from the database using Node.js & MySQL, you will have to configure the following steps
1. Create New Folders & Files
First of all, Install Express Application and Create the following new folders & files
nodeapp/ |__controllers/ | |__image-controller.js |__models/ | |__image-model.js |__public/ | |__images/ |__routes/ | |__image-route.js |__views/ | |__display-image.ejs |__app.js |__database.js
2. Create MySQL Database & Table
You must create a Database with the name nodeapp
Create a table with the name images
into the MySQL database nodeapp
Table Name – images
CREATE TABLE `images` ( `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT, `image_name` varchar(255) DEFAULT NULL )
3. Connect Node.js App to MySQL Database
- First, make sure the MySQL module must be installed
- Create
database.js
in thenodeapp
and write the Node.js MySQL database connection script
File Name – database.js
var mysql = require('mysql'); var conn = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'nodeapp' }); conn.connect(function(err) { if (err) throw err; console.log('Database is connected successfully !'); }); module.exports = conn;
4. Save Image in MySQL Table
Before displaying images on the web page, you must upload images to the folder. Even you must store the image path in the database.
If you don’t have any idea to upload & store images then you should open the following URL to learn it with some simple steps
How to store images in MySQL database using Node.js
Now, Let’s go to the next steps –
How to Display Uploaded Image in Node.js
1. Fetch Image Path From Database
You have to fetch the path from the database through the Model. So, Implement it according to the following steps –
- Include a database connection using
require('../database')
- Create
displayImage
method within themodule.exports
object. - After that, write the SQL query to fetch the image path from the database.
- Pass the fetched image path to the
callback
method then return it.
File Name – image-model
var db=require('../database'); module.exports={ displayImage:function(callback){ // check unique email address var sql='SELECT image_name FROM images'; db.query(sql,function (err, data, fields) { if(err) throw err return callback(data); }) } }
2. Pass Image Path to the page
You have to pass the image path to the view page through the Controller. So, Implement it according to the following steps –
- Include Multer module using
require('multer')
- Also, Include the Model using
require('../models/image-model')
- Create a custom method to display an image within the
module.exports
object - Access the
displayImage
the method from the model. - Pass image path with
imagePath
to thedisplay-image.ejs
File Name – image-controller.js
var multer = require('multer'); var imageModel= require('../models/image-model'); module.exports={ displayImage:function(req,res){ imageModel.displayImage(function(data){ res.render('display-image',{imagePath:data}) }) } }
3. Display Image on the Page
You have to display an image on the view page. So, Implement it according to the following steps –
The image path comes with imagePath
from the controller file. Now, use the forEach
loop and print path within the img
tag. In this way, All the images will be successfully shown on the view page.
If No Image path saves in the database then you will get a message like “No Image in the Database”
File Name – display-image.ejs
!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <% if(imagePath.length!=0){ imagePath.forEach(function(data){ %> <img src="/images/<%=data.image_name; %>" width="200px"> <% }) %> <% } else{ %> <p>No Image in the Database</p> <% } %> </body> </html>
4. Create a Route to display Image
You must create a route to display images. To implement it through the following steps –
- Include express module
- Acess
Router()
method from the express - Include controller file using
require('../controllers/display-image')
- Create a route /display-image with
GET
method to display an image on the web page - At last, the export router module
File Name – image-route.js
const express = require('express'); const router = express.Router(); const imageController= require('../controllers/image-controller'); router.get('/display-image',imageController.displayImage); module.exports = router;
5. Include a Route in the app.js
By default, many lines of code are written in the app.js file that is not shown here. You have also to include the route in the main root file app.js.
File Name – app.js
var imageRouter = require('./routes/image-route'); app.use('/', imageRouter);
6. Run Node.js app to display Image
Just Enter the following URL to display images on the web page
http://localhost:3000/display-image