04-Apr-2023
.
Admin
Hello Friends,
React JS + Node JS Express + MySQL Image Upload Example. This tutorial will guide you on how to upload images to a MySQL database using Node JS Express and ReactJS. Through this tutorial, you can use a React JS app to upload images.
we will learn how to upload image in mysql using node js and react js. I would like to show you upload image in mySQL using node js and react js. you will learn how to upload images in mysql. We will look at example of handling file uploads in node.js with the express.
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.cssfile 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:
For Install Node js on Ubuntu :
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
#Node JS