Hello to all, welcome back to codeat21. I am going to tell you, React single image upload to the Node js server and store the images in the MySQL database.
React is an open-source JavaScript library, It is not a framework. React app developing Single Page Applications (SPA). A React app is creating multiple components, it is responsible for client-side rendering a reusable piece of HTML. It is an open-source library(JavaScript) that is used for developing user interfaces. The language used is JavaScript and JSX. React js Used Virtual DOM (Document Object Model) that makes it faster.
Node.js is open-source that is used server-side. It is not a framework and a programming language. A model view controller(MVC) framework supports Node.js. The only language used javascript. It runs on chrome’s v8 engine and no DOM (Document Object Model) is used.
Install React App
Now, let’s create React app(create-react-app). Open your terminal and press enter the following command.
npx create-react-app react-node-imageupload
Go to the project folder:
cd react-node-imageupload
Axios is an HTTP client based on the XMLHttpRequests service that works both in the browser and in a Node.js environment. It is based on the Fetch API and the XMLHttpRequest interface provided by browsers. It’s more powerful, flexible, and easy to customize. It’s is a third-party library.it is supported in all modern web browsers and Internet Explorer 8+.
And finally, let’s Axios Install the required packages using the npm command:
npm install axios
Run your React app in the web browser:
npm start
Run your project on this URL: localhost:3000
App.jsimport React,{useState } from 'react'; import axios from 'axios'; import './App.css'; function App() { const [userInfo, setuserInfo] = useState({ file:[], filepreview:null, }); const handleInputChange = (event) => { setuserInfo({ ...userInfo, file:event.target.files[0], filepreview:URL.createObjectURL(event.target.files[0]), }); } const [isSucces, setSuccess] = useState(null); const submit = async () =>{ const formdata = new FormData(); formdata.append('avatar', userInfo.file); axios.post("http://localhost:8080/imageupload", formdata,{ headers: { "Content-Type": "multipart/form-data" } }) .then(res => { // then print response status console.warn(res); if(res.data.success === 1){ setSuccess("Image upload successfully"); } }) } return ( <div className="container mr-60"> <h3 className="text-white">React Image Upload And Preview Using Node Js - <span> codeat21.com </span> </h3> <div className="formdesign"> {isSucces !== null ? <h4> {isSucces} </h4> :null } <div className="form-row"> <label className="text-white">Select Image :</label> <input type="file" className="form-control" name="upload_file" onChange={handleInputChange} /> </div> <div className="form-row"> <button type="submit" className="btn btn-dark" onClick={()=>submit()} > Save </button> </div> </div> {userInfo.filepreview !== null ? <img className="previewimg" src={userInfo.filepreview} alt="UploadImage" /> : null} </div> ); } export default App;
NodeJs — Setting Up the Project
Now, let’s start a new Node.js project. Build a separate package.json file to access your dependencies:
npm init
Here, the one by one install some dependencies are cors, express, and multer via npm(Node Package Manager).
npm install cors
npm install express
npm install --save multer
npm install --save mysql2
npm install -g nodemon
my package.json file look like the following –
package.json{ "name": "react-image-upload", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "codeat21", "license": "ISC", "dependencies": { "cors": "^2.8.5", "express": "^4.17.1", "multer": "^1.4.2", "mysql2": "^2.2.5" } }
index.jsconst express = require('express') const app = express(); const path = require('path'); const cors = require('cors'); const multer = require('multer'); const port = process.env.PORT || 8080; // Databse Connection const connection = require('./config/database'); app.use(cors()); const storage = multer.diskStorage({ destination: path.join(__dirname, '../public_html/', 'uploads'), filename: function (req, file, cb) { // null as first argument means no error cb(null, Date.now() + '-' + file.originalname ) } }) app.post('/imageupload', async (req, res) => { try { // 'avatar' is the name of our file input field in the HTML form let upload = multer({ storage: storage}).single('avatar'); upload(req, res, function(err) { // req.file contains information of uploaded file // req.body contains information of text fields if (!req.file) { return res.send('Please select an image to upload'); } else if (err instanceof multer.MulterError) { return res.send(err); } else if (err) { return res.send(err); } const classifiedsadd = { image: req.file.filename }; const sql = "INSERT INTO users SET ?"; connection.query(sql, classifiedsadd, (err, results) => { if (err) throw err; res.json({ success: 1 }) }); }); }catch (err) {console.log(err)} }) app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
Images Upload and store the images name into the MySQL database
In the following example, we will start how to React single images upload and store the name of the images into the MySQL database using Node js.
- Database Name – Codeat21
- Table Name – users
codeat21CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `image` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
database.jsconst util = require('util'); const mysql = require('mysql2'); const pool = mysql.createPool({ connectionLimit: 10, host : 'localhost', user : 'root', password : '', database : 'codeat21' }); // Ping database to check for common exception errors. pool.getConnection((err, connection) => { if (err) { if (err.code === 'PROTOCOL_CONNECTION_LOST') { console.error('Database connection was closed.'); } if (err.code === 'ER_CON_COUNT_ERROR') { console.error('Database has too many connections.'); } if (err.code === 'ECONNREFUSED') { console.error('Database connection was refused.'); } } if (connection) connection.release(); return; }); // Promisify for Node.js async/await. pool.query = util.promisify(pool.query); module.exports = pool;
Conclusion
Finally, React image upload and preview with Nodejs, Express js, and multer Tutorial is over. In this article, we learned to React image upload a single file in React js app and store the images in the MySQL database using the Node js server.
Anyway, if you want the full source code for the React single image upload and preview example in our Github repository. https://github.com/CodeAT21 This link is a CodeAT21 Github repository