In this article, we’ll look at how to image resize before uploading in a React app. We can image resize, and compress the images based on our requirements. our compress your images follow these simple steps are : The first step is to install the package using yarn/npm. The next one is image resizing- height & width manipulation and different cropping options.

Install React App

Now, Open your terminal and press enter the following command.

npx create-react-app react-node-imageupload 
cd react-node-imageupload 
npm install axios
npm start
Image Resize Code
const handleInputChange = (event) => { const imageFile = event.target.files[0]; const imageFilname = event.target.files[0].name; if (!imageFile) { setinvalidImage('Please select image.'); return false; } if (!imageFile.name.match(/\.(jpg|jpeg|png|JPG|JPEG|PNG|gif)$/)) { setinvalidImage('Please select valid image JPG,JPEG,PNG'); return false; } reader.onload = (e) => { const img = new Image(); img.onload = () => { //------------- Resize img code ---------------------------------- var canvas = document.createElement('canvas'); var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); var MAX_WIDTH = 437; var MAX_HEIGHT = 437; var width = img.width; var height = img.height; if (width > height) { if (width > MAX_WIDTH) { height *= MAX_WIDTH / width; width = MAX_WIDTH; } } else { if (height > MAX_HEIGHT) { width *= MAX_HEIGHT / height; height = MAX_HEIGHT; } } canvas.width = width; canvas.height = height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, width, height); ctx.canvas.toBlob((blob) => { const file = new File([blob], imageFilname, { type: 'image/jpeg', lastModified: Date.now() }); setuserInfo({ ...userInfo, file:file, filepreview:URL.createObjectURL(imageFile), }) }, 'image/jpeg', 1); setinvalidImage(null) }; img.onerror = () => { setinvalidImage('Invalid image content.'); return false; }; //debugger img.src = e.target.result; }; reader.readAsDataURL(imageFile); };
index.js
import React,{useState } from 'react'; import axios from 'axios'; import './App.css'; function App () { const [userInfo, setuserInfo] = useState({ file:[], filepreview:null, }); const [invalidImage, setinvalidImage] = useState(null); let reader = new FileReader(); const handleInputChange = (event) => { const imageFile = event.target.files[0]; const imageFilname = event.target.files[0].name; if (!imageFile) { setinvalidImage('Please select image.'); return false; } if (!imageFile.name.match(/\.(jpg|jpeg|png|JPG|JPEG|PNG|gif)$/)) { setinvalidImage('Please select valid image JPG,JPEG,PNG'); return false; } reader.onload = (e) => { const img = new Image(); img.onload = () => { //------------- Resize img code ---------------------------------- var canvas = document.createElement('canvas'); var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); var MAX_WIDTH = 437; var MAX_HEIGHT = 437; var width = img.width; var height = img.height; if (width > height) { if (width > MAX_WIDTH) { height *= MAX_WIDTH / width; width = MAX_WIDTH; } } else { if (height > MAX_HEIGHT) { width *= MAX_HEIGHT / height; height = MAX_HEIGHT; } } canvas.width = width; canvas.height = height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, width, height); ctx.canvas.toBlob((blob) => { const file = new File([blob], imageFilname, { type: 'image/jpeg', lastModified: Date.now() }); setuserInfo({ ...userInfo, file:file, filepreview:URL.createObjectURL(imageFile), }) }, 'image/jpeg', 1); setinvalidImage(null) }; img.onerror = () => { setinvalidImage('Invalid image content.'); return false; }; //debugger img.src = e.target.result; }; reader.readAsDataURL(imageFile); }; 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">Uploading and Resizing Images with ReactJS - <span> codeat21.com </span> </h3> <div className="formdesign"> {isSucces !== null ? <h4> {isSucces} </h4> :null } {invalidImage !== null ? <h4 className="error"> {invalidImage} </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
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.js
const 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) { 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 imageResize = { image: req.file.filename } const sql = "INSERT INTO posts SET ?"; connection.query(sql, imageResize, (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}`))

Resize 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
codeat21
CREATE 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.js
const 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;