React Image Upload with Preview Example Tutorial

React Image Upload with Preview Example Tutorial

Create an image upload form in HTML to allow users to select a file for upload, and use createObjectURL with state to show a preview on the component in a React JS application.

In this tutorial, you will learn in detail how to show image preview before uploading to server in React JS app.

How to Show Preview Image Before Upload in React

Steps to create an image preview feature before upload:

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

Run the following command to install boostrap 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.

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.

Recommended Posts

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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