Clue Mediator

Validate Image Content in ReactJS

šŸ“…January 21, 2020
šŸ—ReactJS

Today we will show you how to validate image content in ReactJS. When we are working with the image upload functionality then we also need to implement the validation for the image content as well.

Validate image size, extension and type in ReactJS, Validate file upload in React JS, file upload validation in reactjs, Implement validation in file upload, How to validate upload file size and file extension using React JS.

Checkout more articles on ReactJS

Everyone knows about the image validation based on the extension but we also need to implement the validation for the image content in ReactJS.

What is image content validation?

Letā€™s give you an example to understand it. First, create a text file (`.txt`) and then change the extension of the same file from `.txt` to `.png`. After that when you upload this file then it will pass the extension validation but still, itā€™s invalid so we need to prevent it to upload on the server.

Way to validate image content in ReactJS

  1. Image upload in ReactJS
  2. Implement image content validation
  3. Output

1. Image upload in ReactJS

Letā€™s begin with the very basic example of the image upload in ReactJS. If you donā€™t know how to upload an image in ReactJS then go through the link below.

Image upload in ReactJS

2. Implement image content validation

Here we will validate the image in two different ways.

  • Validate image extension: For that we will match the file name extension.
  • Validate image content: For that we have to use `FileReader()` to read the file and it will return the image in `base64` string. So when we load it in image object then it will throw an error if image is invalid.

We covered both validations in the below code.

constructor(props) {
  ...
  ...
  this.reader = new FileReader();
}
...
...
// handle change event of input file and validate it
onChangeFile = event => {
  const imageFile = event.target.files[0];

  if (!imageFile) {
    this.setState({ invalidImage: 'Please select image.' });
    return false;
  }

  if (!imageFile.name.match(/\.(jpg|jpeg|png|gif)$/)) {
    this.setState({ invalidImage: 'Please select valid image.' });
    return false;
  }

  this.reader.onload = (e) => {
    const img = new Image();
    img.onload = () => {
      this.setState({ selectedFile: imageFile, invalidImage: null });
    };
    img.onerror = () => {
      this.setState({ invalidImage: 'Invalid image content.' });
      return false;
    };
    img.src = e.target.result;
  };
  this.reader.readAsDataURL(imageFile);
}

Letā€™s combine all the code together to see how it looks.

Here, We need server support in form of API to upload image to a server. For that we have to create the file upload API in Node.js. Please refer below link if you don't know about it.

File upload API in Node.js

App.js

import React, { Component } from 'react';
import axios from 'axios';

// base url of API
const BASE_URL = 'http://localhost:4000/';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedFile: null, // to store selected file
      handleResponse: null, // handle the API response
      imageUrl: null, // to store uploaded image path
      invalidImage: null // handle the message of the image validation
    };
    this.reader = new FileReader();
  }

  // handle change event of input file and validate it
  onChangeFile = event => {
    const imageFile = event.target.files[0];

    if (!imageFile) {
      this.setState({ invalidImage: 'Please select image.' });
      return false;
    }

    if (!imageFile.name.match(/\.(jpg|jpeg|png|gif)$/)) {
      this.setState({ invalidImage: 'Please select valid image.' });
      return false;
    }

    this.reader.onload = (e) => {
      const img = new Image();
      img.onload = () => {
        this.setState({ selectedFile: imageFile, invalidImage: null });
      };
      img.onerror = () => {
        this.setState({ invalidImage: 'Invalid image content.' });
        return false;
      };
      debugger
      img.src = e.target.result;
    };
    this.reader.readAsDataURL(imageFile);
  }

  // handle click event of the upload button
  handleUpload = () => {
    const { selectedFile } = this.state;
    if (!selectedFile) {
      this.setState({
        handleResponse: {
          isSuccess: false,
          message: "Please select image to upload."
        }
      });
      return false;
    }
    const formData = new FormData();
    formData.append('dataFile', selectedFile, selectedFile.name);
    axios.post(BASE_URL + 'uploadfile', formData).then(response => {
      this.setState({
        handleResponse: {
          isSuccess: response.status === 200,
          message: response.data.message
        },
        imageUrl: BASE_URL + response.data.file.path
      });
    }).catch(err => {
      alert(err.message);
    });
  }

  render() {
    const { handleResponse, imageUrl, invalidImage } = this.state;
    return (
      <div className="App" >
        <h4>Validate Image Content in ReactJS - Clue Mediator</h4>

        <p className="title">Select Image:</p>
        <div style={{ marginBottom: 10 }}>
          <input type="file" onChange={this.onChangeFile} />
        </div>
        {invalidImage && <p className="error">{invalidImage}</p>}
        <input type="button" value="Upload" onClick={this.handleUpload} />
        {handleResponse && <p className={handleResponse.isSuccess ? "success" : "error"}>{handleResponse.message}</p>}

        <p className="title" style={{ marginTop: 30 }}>Uploaded Image:</p>
        {imageUrl && <img src={imageUrl} alt="Uploaded File" height="100" width="100" />}
      </div>
    );
  }
}

export default App;

3. Output

Output - Validate Image Content in ReactJS - Clue Mediator

Output - Validate Image Content in ReactJS - Clue Mediator

Thank you for the reading. Happy Coding!

Demo & Source Code

Github Repository StackBlitz Project