• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • About Us
  • Privacy Policy
  • Disclaimer
  • Terms And Conditions
  • Contact Us

CodingStatus

- Learn to Build Web Applications

  • Home
  • HTML
  • CSS
  • JavaScript
  • jQuery
  • Ajax
  • Node.js
  • PHP
  • Tips

How to Store Image in MySQL Database Using Node.js

November 13, 2020 By Noor Khan Leave a Comment

In this tutorial, You will learn how to store image in a MySQL database using Node.js & express application. Even you implement it with some simple steps & MVC like model, view & controller. Once you complete all the given steps, you will easily upload single or multiple images to the folder and also store the image path in the database.

how to store image in mysql database using node.js

Contents

  • Upload Image and Store Path in Database Using Node.js & MySQL
    • 1. Create New Folders & Files
    • 2. Create MySQL Database & Table
    • 3. Connect Node.js App to MySQL Database
    • 4. Install Multer Module
  • Store Image Path in MySQL Database Using Node.js
    • 1. Create an Image upload form
    • 2. Store Image Path in Database
    • 3. Upload Image to the Folder
    • 4. Upload & store image
    • 5. Create Routes to upload & store Image
    • 6. Include Routes in root file app.js
    • 7. Run Node.js App to upload & store Image

Upload Image and Store Path in Database Using Node.js & MySQL

Before upload and store image in the database using Node.js & MySQL, you must set up the following steps

Learn also –

How to Upload Multiple Files Using Multer in Node.js

1. Create New Folders & Files

First of all, Install Express Application and Create the following new folders & files

nodeapp/
  |__controllers/
  |     |__store-image.js
  |__middlewares/
  |     |_store-image.js
  |__models/
  |     |__store-image.js
  |__public/
  |     |__images/
  |__routes/
  |     |__store-image.js
  |__views/
  |     |__image-upload-form.ejs
  |__app.js
  |__database.js

2. Create MySQL Database & Table

you must create a Database with the name nodeapp

CREATE DATABASE nodeapp

 

Create a table with the name  image into the MySQL database nodeapp

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 the nodeapp 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. Install Multer Module

Multer module helps us to upload images easily. So, you must install it with the help of the following command

nodeapp> npm install --save multer

Store Image Path in MySQL Database Using Node.js

Now, you have to follow all the next steps to upload & store the image in the MySQL database.

1. Create an Image upload form

You have to declare three main attributes within the form tag.

  • action=”/store-image” – It will redirect to /store-image through the POST method when you submit the form.
  • method=”POST” – It will send your image information with security.
  • enctype=”multipart/form-data” – It handles file uploading request.

Even you have to declare three attributes within the input field

  • type=”file” – It creates a browse Button to select any files from your device
  • name=”image” – You will need it to access image information
  • multiple – It allows us to select multiple files/images at a time

Path – views/image-upload-form.ejs

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    
<form action="/store-image" method="POST" enctype="multipart/form-data">
    <label>Store Image</label><br><br>
    <p><%=(typeof alertMsg!='undefined')? alertMsg:''%></p>
    <input type="file"  name="image" multiple>
    <button type="submit">Upload</button>
</form>

</body>
</html>

 

2. Store Image Path in Database

You can store images through the Model. So, configure the following steps – –

  • Create a folder controllers
  • Also, Create a file store-image.js in the controllers
  • Create a function storeImage with two parameters inputValues & callback.  Where inputValues will take image value from the controller method
  • After that, write a SQL query to fetch the image name from the database and check the image is already existed or not.
  • Also, Write a SQL query to store image path in the database
  • At last, return a message to the callback method

Path – models/store-image.js

var db=require('../database');
module.exports={ 
  storeImage:function(inputValues,callback){

  // check unique email address
var sql='SELECT * FROM images WHERE image_name =?';
db.query(sql,inputValues.image_name,function (err, data, fields) {
 if(err) throw err
 if(data.length>1){
     var msg = inputValues.image_name + " is already exist";
 }else{ 
    // save users data into database
    var sql = 'INSERT INTO images SET ?';
   db.query(sql, inputValues, function (err, data) {
      if (err) throw err;
   });
  var msg = inputValues.image_name+ "is uploaded successfully";
 }
 return callback(msg)
})
  }
}

3. Upload Image to the Folder

You also have to upload images to the folder through the Middleware. So, configure the following steps – –

  • Create a folder middlewares
  • Also, create a file store-image.js in the middlewares
  • Write the file upload script in the store-image.js
  • Declare image folder path in the code cb(null, 'image_folder_path')

Path – middlewares/store-image

var multer = require('multer');

module.exports.image={
    storage:function(){
        var storage = multer.diskStorage({
        destination: function (req, file, cb) {
          cb(null, 'public/images/')
        },
        filename: function (req, file, cb) {
            cb(null, file.originalname)
        }
      })
      return storage;
},
allowedImage:function(req, file, cb) {
    // Accept images only
    if (!file.originalname.match(/\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF)$/)) {
        req.fileValidationError = 'Only image files are allowed!';
        return cb(new Error('Only image files are allowed!'), false);
    }
    cb(null, true);
}}

4. Upload & store image

You have to upload & store images in both folder & database through the controller. So, configure the following steps –

  • Include Multer module require('multer')
  • Also, include a middleware file using require('../middlewares/store-image')
  • Include a model file using require('../models/store-image')
  • Create a method imageUploadForm to display image upload form
  • Even create another method storeImage to upload & store image

Path – controllers/store-image.js

var multer  = require('multer');
var storeImageMiddleware= require('../middlewares/store-image');
var storeImageModel= require('../models/store-image');

module.exports={
    imageUploadForm:function(req,res){
        res.render('image-upload-form');
     },
     storeImage:function(req,res){
        var upload = multer({
                    storage: storeImageMiddleware.image.storage(), 
                    allowedImage:storeImageMiddleware.image.allowedImage 
                    }).single('image');
        upload(req, res, function (err) {
           if (err instanceof multer.MulterError) {
              res.send(err);
           } else if (err) {
              res.send(err);
           }else{
              // store image in database
               var imageName = req.file.originalname;
               var inputValues = {
                  image_name: imageName
               }
             // call model
             storeImageModel.storeImage(inputValues, function(data){
               res.render('image-upload-form',{alertMsg:data})
             })
              
           }
           
        })
        
     }
}

5. Create Routes to upload & store Image

Create two routes to upload & store image using the following steps –

  • Include a controller file using require('../controllers/store-image')
  • Create a route /store-image  with the GET method to display image upload form
  • Also, Create another route /store-image with the POST method to upload & store Images. This route will be called when you submit the image upload form.

Path – routes/store-image.js

const express = require('express');
const router = express.Router();
const storeImageController= require('../controllers/store-image');

router.get('/store-image',storeImageController.imageUploadForm);

router.post('/store-image',storeImageController.storeImage);

module.exports = router;

6. Include Routes in root file app.js

By default app.js file has many lines of code that are not shown here. But you can also include store image routes in this file using the following two steps –

Include the store image route just below the code require('./routes/users')

var storeImageRouter = require('./routes/store-image');

 

Also, use the store image route just below the app.use('/', usersRouter);

app.use('/', storeImageRouter);

7. Run Node.js App to upload & store Image

First of all, Enter the following URL in your web browser and press the ENTER key. then, an image upload form will be shown. After that, select images from your computer and submit the button.

http://localhost:3000/store-image

When you submit the image upload form then /store-image will be called with POST method and images will be saved in the folder & its path will be stored in the database successfully.

Filed Under: Node.js

You may like also

  1. Node.js File Upload Using Express Multer
  2. Upload Multiple Files Using Multer in Node.js and Express
  3. Node.js MySQL CRUD Operation with Example
  4. How to Display Image From MySQL Database in Node.js

Hey there, Welcome to CodingStatus. My Name is Noor Khan from Bihar, India. I'm a Software Engineer. I have been working in the Web Technology field for 3 years. Here, I blog about Web Development & Designing. Even I help developers to build the best Web Applications.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Follow us

  • facebook
  • twitter
  • linkedin
  • pinterest

Recent Posts

  • How to Learn Web Development Step by Step
  • How to Learn Web Designing From Basics
  • How to Become a Programmer Step By Step
  • 10 Best Google Chrome Extensions for Web Developers
  • Top 10 Web Designing Languages for Beginners

Latest Node.js Tutorials

  • Fetch data from MongoDB Using Mongoose and Node.js Express
  • Node.js Form Validation with an Example
  • Upload Multiple Files Using Multer in Node.js and Express
  • Node.js File Upload Using Express Multer
  • How to Display Image From MySQL Database in Node.js
  • Home
  • About Us
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
  • Sitemap
  • Contact Us

Copyright © 2021 CodingStatus - All Rights Reserved