NodejsReactjs

Reactjs Nodejs Image Upload Validation

Reactjs Nodejs Image Upload Validation

Hello friends, welcome back to my blog. Today in this blog post, I am going to tell you, Reactjs Nodejs Image Upload Validation.

Reactjs Nodejs Image Uploading

For reactjs new comers, please check the below link for basic understanding:

Reactjs Basic Tutorials


Here is the working code snippet for Reactjs Nodejs Image Upload Validation and please use carefully and avoid mistakes:

1. Firstly friends we need reactjs fresh setup and for then we need to run below commands into our terminal and also we should have latest node version installed on our pc:

npx create-react-app reactnode

cd reactnode

npm start

 

2. Now friends we need to run below commands also to have  axios module into our reactjs application:

npm install axios //API Service

npm start //start the application

 

3. Now, we need to add below code into our src/app.js file or you can replace below code with existing one that you have into your src/app.js file:

import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import axios from 'axios';
//Success POPUP
import Swal from 'sweetalert2'
class Demo extends React.Component
{
  constructor(props)
  {
    super(props);
    
    this.state = {
      imagedata : String
    };
    this.addFormData = this.addFormData.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }
  //FileChange
  handleChange(file)
  {
    
    this.setState({ 
      imagedata: file[0],
    })
  }
  //Form Submission
  addFormData(evt)
    {
        evt.preventDefault();
        const fd = new FormData();
        if(this.state.imagedata.name.split('.').pop() !=="jpg")
        {
          //Success Message in Sweetalert modal
          Swal.fire({
            title: 'Image should be in JPG format only.',
            type: 'warning',
            
          });
          this.myFormRef.reset();
        }
        else
        {
        fd.append('image', this.state.imagedata);
      
        //Post Request to laravel API Route
        axios.post('http://localhost:8000/upload', fd
        ).then(res=>
          {
        this.myFormRef.reset();
        //Success Message in Sweetalert modal
        Swal.fire({
          title: 'Image has been uploaded successfully.',
          text: "Thanks",
          type: 'success',
          
        });
        
        }
        );
    }
    }
  render()
  {
    return (
        <div>
            
            <div className="jumbotron text-center">
                <h3>Therichpost.com<br>
                </br>Reactjs Nodejs Image Upload Validation</h3>
            </div>
      

            <div className="container">
            
            <form ref={(el) => this.myFormRef = el}>
               
                
               <label for="image">Image Upload:</label>
               <input className="form-control" onChange={ (e) => this.handleChange(e.target.files) } type="file" id="image" ref="productimage" />
              
               
               <button type="submit" className="btn btn-primary mt-5" onClick={this.addFormData}>Submit</button>
           </form>
               
                    </div>
            
        </div>
    )
  }
}
export default Demo;

 


1. Now friends, we need to create new folder name ‘nodeproject’ and inside it open new terminal and run below commands:

npm i express express-fileupload cors

2. Now friends, we need to create new file name ‘nodejs’ and add below code inside that file:

const express = require('express');
const fileUpload = require('express-fileupload');
const cors = require('cors')
const app = express();
// middle ware
app.use(express.static('public')); //to access the files in public folder
app.use(cors()); // it enables all cors requests
app.use(fileUpload());
// file upload api
app.post('/upload', (req, res) => {
    if (!req.files) {
        return res.status(500).send({ msg: "file is not found" })
    }
        // accessing the file
    const myFile = req.files.image;
    //  mv() method places the file inside public directory
    myFile.mv(`${__dirname}/public/${myFile.name}`, function (err) {
        if (err) {
            console.log(err)
            return res.status(500).send({ msg: "Error occured" });
        }
        // returing the response with file path and name
        return res.send({name: myFile.name, path: `/${myFile.name}`});
    });
})
app.listen(8000, () => {
    console.log('server is running at port 8000');
})

3. Now friends, we need to create folder name ‘public’ inside ‘nodeproject’ folder.

4. Now friends, we need to run below command to start node server:

node node.js

Now we are done friends. If you have any kind of query or suggestion or any requirement then feel free to comment below.

Note: Friends, I just tell the basic setup and things, you can change the code according to your requirements. For better understanding and live working must watch video above.

I will appreciate that if you will tell your views for this post. Nothing matters if your views will good or bad.

Jassa

Thanks

Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know Wordpress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, Angular 8, Angular 9, Angular 10, Angular 11, Nodejs, laravel, Codeigniter, Shopify, Squarespace, Jquery, Google Map Api, Vuejs, Reactjs, Bigcommerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.