How To Upload And Preview Image In React JS

Websolutionstuff | Sep-06-2022 | Categories : React JS

In this article, we will see how to upload and preview images in react js. You can learn how to show an image preview before uploading it to the server in a react js. If you want to show a preview of the image before uploading it into your react app. So, we will create a simple react js app that will use an HTML file input field along with some events to show an image preview. For the backend, we will use a simple PHP application that exposes a unique endpoint that accepts a POST request containing the file/image to upload an image.

So, let's see react js image upload with preview and react js image upload with preview display.

Step 1: Create React App

Step 2: Install Axios and Bootstrap 4

Step 3: Create Simple Image Upload with Preview Component

Step 4: Add Component in App.js

Step 5: Create PHP File

 

Step 1: Create React App

In this step, we will create a new react app using the following command.

npx create-react-app my-react-app

To run the react app, execute the following command on your terminal.

npm start

 

 

Step 2: Install Axios and Bootstrap 4

In this step, we will install bootstrap 4 libraries into react app.

npm install bootstrap --save

npm install axios --save

Add bootstrap.min.css file in src/App.js file:

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
 
function App() {
  return (
    <div>
      <h2>How To Upload And Preview Image In React JS - Websolutionstuff</h2>
    </div>
  );
}
 
export default App;

 

Step 3: Create Simple Image Upload with Preview Component

In this step, we will create the ImageUploadPreviewComponent.js component.

import React, { Component } from 'react';
import axios from 'axios';
 
class ImageUploadPreviewComponent extends Component {
 
    constructor(props) {
        super(props)
        this.state = {
            file: null
        }
        this.uploadSingleFile = this.uploadSingleFile.bind(this)
        this.upload = this.upload.bind(this)
    }
 
    uploadSingleFile(e) {
        this.setState({
            file: URL.createObjectURL(e.target.files[0])
        })
    }
 
    upload(){
        const formData = { image: this.state.file }
         
        let url = "http://localhost:8000/upload.php";
        axios.post(url, formData, { // receive two parameter endpoint url ,form data 
        })
        .then(res => { // then print response status
            console.warn(res.data);
        })
 
    }
 
    render() {
        let imgPreview;
        if (this.state.file) {
            imgPreview = <img src={this.state.file} alt='' />;
        }
        return (
            <form>
                <div className="form-group preview">
                    {imgPreview}
                </div>
 
                <div className="form-group">
                    <input type="file" className="form-control" onChange={this.uploadSingleFile} />
                </div>
                <button type="button" className="btn btn-primary btn-block" onClick={this.upload}>Upload</button>
 
            </form >
        )
    }
}

To upload the file you need an HTML template. In this template, you will create a `file input` element that allows us to choose the file and a button to upload a file. So, defined the if statement inside the render() method.

Note: The `uploadSingleFile` method will be called when the user chooses a file. It will get the file object of the selected file and store it in the `file` state. And will use a simple PHP application that exposes a unique endpoint that accepts a POST request containing the file/image to upload the image to the server.

 

 

Step 4: Add Component in App.js

In this step, we will add the ImageUploadPreviewComponent.js file in src/App.js file.

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import ImageUploadPreviewComponent from './ImageUploadPreviewComponent'
 
function App() {  
     
  return (  
    <div className="App">  
      <ImageUploadPreviewComponent/>  
    </div>  
  );  
}  
 
export default App;

 

Step 5: Create PHP File

 In this step, we will create a PHP file, which names upload.php. And add the following code to it.

 <?php
     
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: PUT, GET, POST");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        
    // Folder Path For Ubuntu
    // $folderPath = "/var/www/my-app/uploads";
    // Folder Path For Window
    $folderPath = "uploads/";
    
    $file_tmp = $_FILES['image']['tmp_name'];
    $file_ext = strtolower(end(explode('.',$_FILES['image']['name'])));
    $file = $folderPath . uniqid() . '.'.$file_ext;
    move_uploaded_file($file_tmp, $file);
    
   return json_encode(['status'=>true]);
?>

 


Recommended Post
Featured Post
Laravel 9 Two Factor Authentication With SMS
Laravel 9 Two Factor Authentic...

In this article, we will see laravel 9 two-factor authentication with SMS. we will send an OTP SMS to the mobile nu...

Read More

Sep-26-2022

Laravel 10 Composer-runtime-api ^2.2 Error - Fixed
Laravel 10 Composer-runtime-ap...

In this article, we will see laravel/framework[v10.0.0, ..., v10.0.3] require composer-runtime-api ^2.2 error fixed...

Read More

Mar-07-2023

Laravel 9 Group Column Chart Using Highcharts
Laravel 9 Group Column Chart U...

In the world of web development, Laravel 9 is a user-friendly PHP framework. When combined with Highcharts, a top JavaSc...

Read More

Jan-02-2023

How to Downgrade PHP 8.2 to 8.1 in Ubuntu
How to Downgrade PHP 8.2 to 8....

Hey there, I recently found myself in a situation where I needed to downgrade my PHP version from 8.2 to 8.1 on my Ubunt...

Read More

Nov-01-2023