Upload Image in MySQL using Node js and React js

Upload Image in MySQL using Node js and React js

React js + Node js Express + MySQL image upload example. This tutorial will guide you on how to upload images in MySQL database using node js express and reactjs.

Through this tutorial; you can use react js app as frontend and node express js app as backend; So, in node js express app will use node multer library to store image into directory of node express js app and upload image into mysql database.

Before start this react js + node express js + MySQL image file upload tutorial; you’ll need to have Node.js installed which can be done by following the instructions on this tutorial.

React JS Upload Image in MySQL database using Node js Express

  • Create React Frontend App
    • Step 1 – Create React App
    • Step 2 – Install Axios and Bootstrap 4
    • Step 3 – Create Image Upload Form Component
    • Step 4 – Import Component in App.js
  • Create Node Express JS Backend
    • Step 1 – Create Node JS Express App
    • Step 2 – Install Express MySQL and cors Dependencies
    • Step 3 – Create Server.js
    • Step 4 – Start Node JS Express App

Create React Frontend App

Step 1 – Create React App

Open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app my-react-app

To run the React app, execute the following command on your terminal:

npm start

Check out your React app on this URL: localhost:3000

Step 2 – Install Axios and Bootstrap 4

Then execute the following command to install axios and boostrap 4 library into your react app:

npm install bootstrap --save

npm install axios --save

Add bootstrap.min.css file in src/App.js file:

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

function App() {
  return (
    <div>
      <h2>upload image in mysql using node js and reactjs</h2>
    </div>
  );
}

export default App;

Step 3 – Create Image Upload Form Component

In this step, visit src directory of your react js app and create a form component named FileUpload.js. And add the following code into it:

import React from 'react'
import axios from 'axios';

class FileUpload extends React.Component{

      const [file, setFile] = useState();
      const [fileName, setFileName] = useState("");

      const saveFile = (e) => {
        setFile(e.target.files[0]);
        setFileName(e.target.files[0].name);
      };

      const uploadFile = async (e) => {
        const formData = new FormData();
        formData.append("file", file);
        formData.append("fileName", fileName);
        try {
          const res = await axios.post(
            "http://localhost:3000/upload",
            formData
          );
          console.log(res);
        } catch (ex) {
          console.log(ex);
        }
      };

    render(){
      return (
        <div className="App">
          <input type="file" onChange={saveFile} />
          <button onClick={uploadFile}>Upload</button>
        </div>
      );
    }
}

export default FileUpload;

Step 4 – Import Component in App.js

In this step, you need to add FileUpload.js file in src/App.js file:

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import FileUpload from './FileUpload'

function App() {  
    
  return (  
    <div className="App">  
      <FileUpload/>  
    </div>  
  );  
}  

export default App;

Create Node Express JS Backend

Step 1 – Create Node JS App

Open your terminal and execute the following command to create node js app:

mkdir my-app

cd my-app

npm init -y

Step 2 – Install Express MySQL and cors Dependencies

Execute the following commands to install imperative npm packages which will help us to create REST APIs for your react image upload in mysql database using node js express app:

npm install express multer body-parser cors  mysql

npm install nodemon --save-dev

Step 3 – Create Server.js File

In this step, create server.js file and add the following code into it:

const express = require('express')
const app = express()
const mysql = require('mysql')
const multer = require('multer')
const path = require('path')
const cors = require("cors");
const bodyParser = require('body-parser');


//use express static folder
app.use(cors());
app.use(express.static("./public"))
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
});

//@type   POST
//route for post data
app.post("/upload", 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 will upload image in mysql database and directory in node express js app:

//@type   POST
//route for post data
app.post("/upload", 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 4 – Start Node JS Express App

Start the server with the following command and then you can test the form:

npm start

OR

nodemon server.js

Conclusion

Upload image in MySQL using node js and react js example tutorial; you have learned how to upload image in MySQL database using node js express and react js.

Recommended React JS + Node Express 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 *