Node JS Express Image Upload to MySQL DB Tutorial

Upload image into MySQL database in node js express; In this tutorial, i am going to show you how to upload image file into MySQL database using node js express and multer package.

Multer is an npm package that makes it easy to handle file uploads. It does it very efficiently, thus it is quite popular. In this article, you will learn how to use Multer to handle multipart/form-data using Node. js, Express and MySQL database.

Upload/store images in MySQL DB using Node. js + Express + Multer

  • Step 1 – Create Node JS App
  • Step 2 – Install Express Body Parser and Multer Modules
  • Step 3 – Create Table in MySQL Database
  • Step 4 – Create Server.js File and Import Modules into it
  • Step 5 – Create Image Upload Routes
  • Step 6 – Create Image Upload Form
  • Step 7 – Start App Server

Step 1 – Create Node JS App

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

mkdir my-app
cd my-app
npm init

Step 2 – Install Express and Multer Modules

Install required node js modules; So execute the following command to install express and multer dependencies in your node js app:

npm install express multer --save
npm install sharp --save

Step 3 – 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 4 – Create Server.js File and Import Modules into it

Create server.js file; so visit your app root directory and create it. The import above installed node js modules into it; as shown below:

const express = require('express');
const multer = require('multer');
const path = require('path');
const sharp = require('sharp');
const bodyparser = require('body-parser')

Step 5 – Create Image Upload Routes

Create routes for image upload; so open your server.js file and add the following routes into it:

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}`))

Step 6 – Create Image Upload Form

Create index.html file; add the following html markup code for file upload form:

<!DOCTYPE html>
<html lang="en">
    <head>
      <title>How to store image path in MySQL database using Node js - Laratutorials.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 - Laratutorials.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>

Step 7 – Start App Server

Execute the following on terminal to start app server:

//run the below command

npm start

after run this command open your browser and hit 

http://127.0.0.1:3000/

Conclusion

Node js express file image upload using multer, sharp and express js. In this tutorial, you have learned how to upload file image using multer, sharp and express js.

Recommended Node JS Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.