Upload/Save Images in MySQL using Node. js, Express & Multer

Upload/Save Images in MySQL using Node. js, Express & Multer

Upload image in mysql using node js express example; In this tutorial, you will learn how to upload or save image file path in MySQL database using Node js express using multer library.

Multer is a node. js middleware for handling multipart/form-data , which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.

Upload/store images in MySQL db using node.js express & multer example tutorial; you will learn step by step on how to upload images into MySQL database and directory in node js express framework with multer library.

Upload/Save Images in MySQL using Node. js, Express & Multer

Let’s follow the following steps to upload/save images in MySQL database using Node js express and multer:

  • Step 1 – Create Node Express js App
  • Step 2 – Create Table in MySQL Database
  • Step 3 – Install express body-parser mysql dependencies
  • Step 4 – Create image Upload Form
  • Step 5 – Create Server.js File
  • Step 6 – Start Node Express Js image Upload App Server

Step 1 – Create Node Express js App

Execute the following command on terminal to create node js app:

mkdir my-app
cd my-app
npm init -y

Step 2 – Create Table in MySQL Database

Execute the following sql query to create a table into your database:

CREATE TABLE users_file(id INT(10) NOT NULL AUTO_INCREMENT, file_src TEXT, PRIMARY KEY(id));

Step 3 – Install express multer body-parser mysql dependencies

Execute the following command on the terminal to express multer ejs body-parser mysql dependencies :

npm install express multer body-parser mysql

Step 4 – Create image Upload Form

Create a form with a `file input` element that allows us to choose the file and a button to submit the form; So create index.html file and add the following code into it:

<!DOCTYPE html>
<html lang="en">
    <head>
      <title>How to store image path in MySQL database using Node js - Tutsmake.com</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
      <h1>How to store image path in MySQL database using Node js - Tutsmake.com</h1>
      <form action="/" enctype="multipart/form-data" method="post">
        <input type="file" name="image" accept='image/*' >
        <input type="submit" value="Upload">
      </form>  
    </body>
</html>

Make sure your form must have enctype="multipart/form-data"attribute and form method should be post.

Step 5 – Create Server.js File

Create server.js file and import express multer body-parser mysql dependencies in server.js; as shown below:

const express = require('express')
const app = express()
const bodyparser = require('body-parser')
const mysql = require('mysql')
const multer = require('multer')
const path = require('path')


//use express static folder
app.use(express.static("./public"))

// body-parser middleware use
app.use(bodyparser.json())
app.use(bodyparser.urlencoded({
    extended: true
}))

// Database connection
const db = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "test"
})

db.connect(function (err) {
    if (err) {
        return console.error('error: ' + err.message);
    }
    console.log('Connected to the MySQL server.');
})

//! Use of Multer
var storage = multer.diskStorage({
    destination: (req, file, callBack) => {
        callBack(null, './public/images/')     // './public/images/' directory name where save the file
    },
    filename: (req, file, callBack) => {
        callBack(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
})

var upload = multer({
    storage: storage
});

//! Routes start

//route for Home page
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

//@type   POST
//route for post data
app.post("/post", upload.single('image'), (req, res) => {
    if (!req.file) {
        console.log("No file upload");
    } else {
        console.log(req.file.filename)
        var imgsrc = 'http://127.0.0.1:3000/images/' + req.file.filename
        var insertData = "INSERT INTO users_file(file_src)VALUES(?)"
        db.query(insertData, [imgsrc], (err, result) => {
            if (err) throw err
            console.log("file uploaded")
        })
    }
});

//create connection
const PORT = process.env.PORT || 3000
app.listen(PORT, () => console.log(`Server is running at port ${PORT}`))

Note that; The following route in server.js will upload image into MySQL database and node js experss app directory:

//@type   POST
//route for post data
app.post("/post", upload.single('image'), (req, res) => {
    if (!req.file) {
        console.log("No file upload");
    } else {
        console.log(req.file.filename)
        var imgsrc = 'http://127.0.0.1:3000/images/' + req.file.filename
        var insertData = "INSERT INTO users_file(file_src)VALUES(?)"
        db.query(insertData, [imgsrc], (err, result) => {
            if (err) throw err
            console.log("file uploaded")
        })
    }
});

Step 6 – Start Node Express Js image Upload App Server

You can use the following command to start upload image in mysql using node js express app server:

//run the below command

npm start

after run this command open your browser and hit 

http://127.0.0.1:3000/

Conclusion

How to upload/store image path in mysql database using node js example; You have learned how to upload and store image path in MySQL database using Node js express using multer library.

Recommended Node JS Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

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