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 10 Change Column Name And Type In Migration
Laravel 10 Change Column Name...

In this article, we will see laravel 10 change column names and data types in migration. Here, we will learn about...

Read More

Apr-19-2023

Change Text Color Based On Background Color Using Javascript
Change Text Color Based On Bac...

In this article, we will see a change text color based on background color using javascript. Sometimes we have requ...

Read More

Dec-25-2020

How to Get Random Record in Laravel 10
How to Get Random Record in La...

Here you will learn how to get random records from DB in laravel using the inRandomOrder() method. Explore an...

Read More

Nov-10-2023

How to Integrate Razorpay Payment Gateway in Laravel
How to Integrate Razorpay Paym...

In this article, we will see the most important and exciting toping about how to integrate razorpay payment gateway in l...

Read More

Jan-06-2021