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
How to Create Artisan Command in Laravel with Arguments Support?
How to Create Artisan Command...

Laravel is a comprehensive framework that provides an extensive range of artisan commands, enabling the automation of di...

Read More

Oct-06-2023

How To Setup And Configuration Angular 15
How To Setup And Configuration...

Setting up and configuring Angular 15, the latest version of the popular JavaScript framework, is a crucial step in star...

Read More

Jun-07-2023

Laravel 9 Import Export CSV/EXCEL File Example
Laravel 9 Import Export CSV/EX...

In this tutorial, I will give you laravel 9 import export csv and excel file example. We will simply create import...

Read More

Feb-19-2022

Laravel 10 Send Bulk Mail Using Queue
Laravel 10 Send Bulk Mail Usin...

In this article, we will see laravel 10 send bulk mail using a queue. Here, we will learn about how to send bulk ma...

Read More

Mar-13-2023