React Image Upload With Preview Tutorial

React JS image upload preview example; In this tutorial, i will show you how to show image preview before uploading to the server in a React js app.

In this tutorial I will create a simple form with react apps. This form can show preview before uploading the image in react apps. So, You can use the following tutorial for show preview of image before upload to server or directory in react apps.

For the backend, this tutorial; i will use a simple PHP application that exposes a unique endpoint that accepts a POST request containing the file/image to upload image.

How to Upload Image Files, Show Image Preview in React Apps

  • Step 1 – Create React App
  • Step 2 – Install Axios and Bootstrap
  • Step 3 – Create Image Upload with Preview Component
  • Step 4 – Import Image Upload with Preview Component in App.js
  • Step 5 – Create PHP File

Step 1 – Create React App

Open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app my-react-app

To run the React app, execute the following command on your terminal:

npm start

Check out your React app on this URL: localhost:3000

Step 2 – Install Axios and Bootstrap 4

Execute the following command to install axios and boostrap 4 library into your 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>React JS Image Upload With Preview</h2>
    </div>
  );
}
export default App;

Step 3 – Create Image Upload with Preview Component

Visit the src directory of your react js app and create an image upload with a preview form component named ImageUploadPreviewComponent.js. And add the following code into it:

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 >
        )
    }
}

export default ImageUploadPreviewComponent;

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

Note that, The `uploadSingleFile` method will be called when the user choose 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 server.

Step 4 – Add Image Upload with Preview Component in App.js

Import 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

Create upload.php file; And add the following code into 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]);
?>

Next, start the PHP server using the following command from the root of your file upload app:

php -S 127.0.0.1:8080

Now, you have a running PHP server that exposes an /upload.php REST endpoint.

Conclusion

React JS image upload preview example; In this tutorial, i have shown in detail on how to show image preview before uploading to the server in a React js app. And how to upload image into server using PHP.

Recommended React Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *