React 17 Image Uploader Example with Preview and PHP Server

React JS 17 Image upload component with preview example is going to be discussed in this tutorial; We will learn how to implement image uploader component with PHP backend to save image on the server using image URL in React JS application. To preview an image before upload, we bind few change events with input…

By.

•

min read

React JS 17 Image upload component with preview example is going to be discussed in this tutorial; We will learn how to implement image uploader component with PHP backend to save image on the server using image URL in React JS application.

To preview an image before upload, we bind few change events with input file control and convert the selected image into a base64 URL; this URL is used to show the image preview and upload to server and save it using backend server PHP code.

How to upload images in React JS app?

Going forward, we will follow these steps to preview the image on selection; then upload it to the filesystem using the backend server.

  1.  Create React Application
  2. Install Axios and Bootstrap Packages
  3. Create Image Upload and Preview Component
  4. Adding Image Uploader Component in App.js
  5. Setup PHP Server
  6. Run React Application

 

 Create React Application

First, let’s create a new React application by executing npx command in the terminal.

$ npx create-react-app react-image-preview-app

Move into the application directory

$ cd react-image-preview-app

 

Install Axios and Bootstrap Packages

After creating the application, install the required packages including Axios and Bootstrap.

Axios is a profound library package used in React js applications to make HTTP calls and handle errors. It can be used to immaculately manage the HTTP operations in React applications.

Bootstrap will be used to quickly style our React application, by importing the bootstrap.min.css in the App.js file.

Execute following npm commands in the CLI terminal

$ npm install axios bootstrap --save

 

Create Image Upload and Preview Component

We will create a new component to have image upload and preview image components. Inside the src folder create a new file image-uploader.component.js file and update with the following code.

import React, { Component } from 'react';
import axios from 'axios';
 
class ImageUploaderComponent extends Component {
 
    constructor(props) {
        super(props)
        this.state = {
            name:null,
            file: null
        }
        this.onFileChange = this.onFileChange.bind(this)
        this.uploadFile = this.uploadFile.bind(this)
    }
 
    onFileChange(e) {
        this.setState({
            name: URL.createObjectURL(e.target.files[0]),
            file: e.target.files[0]
        })
    }
 
    uploadFile(){
        const formData =  new FormData();
        formData.append('image', this.state.file);
        let url = "http://127.0.0.1:8080/upload.php";
        axios.post(url, formData, { // Post the form data to url
        })
        .then(res => { // Upload Response
            console.log(res.data);
        })
 
    }
 
    render() {
        let imgPreview;
        if (this.state.name) {
            imgPreview = <img src={this.state.name} alt='Preview' />;
        }
        return (
            <div className="row">
                <div className="col-12">
                    <div className="form-group preview">
                        {imgPreview}
                    </div>

                    <form>
                        <div className="form-group">
                            <input type="file" name="image" className="form-control" onChange={this.onFileChange} />
                        </div>
                        <button type="button" className="btn btn-primary btn-block" onClick={this.uploadFile}>Upload Image</button>
                    </form>
                </div>
            </div>
            
        )
    }
}

export default ImageUploaderComponent;

The template HTML is having a Form to select the image file and a preview block to show the selected image file. It will be rendered using the render() function with bootstrap styles.

When a user selects a file, onFileChange() function is called, a file object is created and saved into the state variable file.In the form, we are calling the POST() HTTP verb to submit the file to our PHP server, which will be saved into the file system.

 

Adding Image Uploader Component in App.js

Now, we will import our ImageUploaderComponent in the App.js file to render it in React app.

Update the App.js file with the following code.

import './App.css';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import ImageUploaderComponent from './image-uploader.component';

function App() {
  return (
    <div className="App container">
      <ImageUploaderComponent/>  
    </div>
  );
}

export default App;

 

Setup PHP Server

Now we will set up the PHP server by creating a PHP file named upload.php inside the server folder. Update the file with the following code.

Also, create a folder under server/uploads to keep uploaded files, otherwise, an error will be thrown while uploading the images.

<?php 
header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");

$response = array();
$upload_dir = 'uploads/';
$server_url = 'http://127.0.0.1:8000';

if($_FILES['image'])
{
    $image_name = $_FILES["image"]["name"];
    $image_tmp_name = $_FILES["image"]["tmp_name"];
    $error = $_FILES["image"]["error"];

    if($error > 0){
        $response = array(
            "status" => "error",
            "error" => true,
            "message" => "Error uploading the file!"
        );
    }else 
    {
        $random_name = rand(1000,1000000)."-".$avatar_name;
        $upload_name = $upload_dir.strtolower($random_name);
        $upload_name = preg_replace('/\s+/', '-', $upload_name);
    
        if(move_uploaded_file($image_tmp_name , $upload_name)) {
            $response = array(
                "status" => "success",
                "error" => false,
                "message" => "File uploaded successfully",
                "url" => $server_url."/".$upload_name
              );
        }else
        {
            $response = array(
                "status" => "error",
                "error" => true,
                "message" => "Error uploading the file!"
            );
        }
    }

}else{
    $response = array(
        "status" => "error",
        "error" => true,
        "message" => "No file was sent!"
    );
}

echo json_encode($response);
?>

Start the PHP server by executing the below command in the file location.

php -S 127.0.0.1:8080

It will start the PHP server at this location

http://127.0.0.1:8080/upload.php

 

Run React Application

Now, you can run the React application by executing the npm command

$ npm start

It will open the react app in a new tab at this location

Local:            http://localhost:3000
 On Your Network:  http://192.168.29.158:3000

Conclusion

Finally, we are done with React image uploader component with preview tutorial. Here we discussed how to show an image object as a preview after a user selects it from a form. The PHP server is used to save the uploaded image to the file system.

In React app we used the Axios package to enable HTTP calls from the application to the server using POST methods.

Leave a Reply

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