React Image Upload with Preview Example Tutorial

React Image Upload with Preview Example Tutorial

Providing a preview of the file before uploading can help prevent mistakes and improve the user experience. In this tutorial, you will learn in detail on how to show image preview before uploading to the server in a React js app.

Showing a preview of an image is a basic and easy thing. If you want to show a preview of the image before uploading it into your react app. So this tutorial will create a simple react js app in which will use an HTML file input field along with some events to show an image preview.

How to Show Preview Image Before Upload in React

By following these steps, you can easily implement a image preview feature before upload in your React.js application.

  • Step 1 – Create React App
  • Step 2 – Install Axios and Bootstrap 4
  • Step 3 – Create 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, 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

In this step, execute the following command to install 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

In this step, 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 >
        )
    }
}

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 Component in App.js

In this step, you need to add 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, you need to create a php file, which name upload.php. 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

In this tutorial, you have learned how to show a preview of a file before uploading it in a React.js application. By providing a preview, we can improve the user experience and reduce errors. And have used the FileReader API to read the contents of the file and display it as an image or a video. By following these steps, you can easily implement a file preview feature in your React.js application.

Recommended React JS Posts

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

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