React JS PHP Image Upload and Preview Example Tutorial

In this tutorial, you will learn how to create an image upload component in React js application, how to show image preview in react. And, also show you how to store the image in react application using the PHP backend server.

File uploading in React js will be discussed in this guide; we will use the PHP server to handle the image uploading. We will use the React class, component, events to show image preview and uploading.

We will show you how to set up a new react app, how to install and use the Axios library to make the request to the PHP server, how to initialize the PHP backend in react app for testing the file upload.

How to Upload, Preview and Store Image in React Js with PHP Server

  • Step 1: Install React Application
  • Step 2: Install Axios Library
  • Step 3: Create PHP Server File
  • Step 4: Build File Upload and Preview Component
  • Step 5: Update App.Js File
  • Step 6: Evoke Development Server

Install React Application

First, we have to install the react application and it requires given command to be executed from the command prompt.

npx create-react-app react-demo-app

Next, step inside the project.

cd react-demo-app

Install Axios Library

To communicate with the PHP server, we require to install the axios package into the react app. It will allow us to make the POST request to store the image file.

npm install axios

Create PHP Server File

In this step, we require to create the backend/ folder at the root of the react app, after creating the folder, get into it and create uploads/ folder.

The uploads folder will store the image selected and uploaded by the user.

Also, create the backend/server.php and place the suggested code inside the file.

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

$response = array();
$DIR = 'uploads/';
$urlServer = 'http://127.0.0.1:8888';

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

    if($error > 0){
        $response = array(
            "status" => "error",
            "error" => true,
            "message" => "Error uploading the file!"
        );
    }else 
    {
        $FILE_NAME = rand(10, 1000000)."-".$fileName;
        $UPLOAD_IMG_NAME = $DIR.strtolower($FILE_NAME);
        $UPLOAD_IMG_NAME = preg_replace('/\s+/', '-', $UPLOAD_IMG_NAME);
    
        if(move_uploaded_file($tempFileName , $UPLOAD_IMG_NAME)) {
            $response = array(
                "status" => "success",
                "error" => false,
                "message" => "Image has uploaded",
                "url" => $urlServer."/".$UPLOAD_IMG_NAME
              );
        }else
        {
            $response = array(
                "status" => "error",
                "error" => true,
                "message" => "Error occured"
            );
        }
    }

}else{
    $response = array(
        "status" => "error",
        "error" => true,
        "message" => "File not found"
    );
}

echo json_encode($response);
?>

Now, we have to invoke the PHP server, it can be done through the given below command.

php -S 127.0.0.1:8888

Here is the endpoint which will help you to store the image in react app through the post request.

http://127.0.0.1:8888/server.php

Build File Upload and Preview Component

Create components/ directory, FileComponent.js file and add the provided code into the file.

In the FileComponent class set the state for the image object with name and file props, create the small form with input type file bind with the onChange event,

On the other hand define the preview prop, which helps to show the image preview in react.

import React, { Component } from "react";
import axios from 'axios';

class FileComponent extends Component {
  
  constructor(props) {
    super(props)
    this.state = {
        name:null,
        file: null
    }
    this.onChangeImg = this.onChangeImg.bind(this)
    this.uploadImage = this.uploadImage.bind(this)
}

onChangeImg(event) {
    this.setState({
        name: URL.createObjectURL(event.target.files[0]),
        file: event.target.files[0]
    })
}

uploadImage(){
    const formData =  new FormData();
    formData.append('image', this.state.file);
    let url = "http://127.0.0.1:8888/server.php";
    axios.post(url, formData, {
    })
    .then(res => {
        console.log(res.data);
    })

}

render() {
    let preview;
    if (this.state.name) {
        preview = <img src={this.state.name} alt='File preview' />;
    }
    return (
        <>
            <div>
                {preview}
            </div>

            <form>
                <input type="file" name="image" onChange={this.onChangeImg} />

                <button type="button" onClick={this.uploadImage}>Upload</button>
            </form>
        </>
    )
}
}


export default FileComponent;

Update App.Js File

Let the React know there is a new component which needs to be registered for managing image uploading.

Consequently, update your App.Js file with the given code.

import React from 'react';
import './App.css';

import FileComponent from './components/FileComponent';

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

export default App;

Evoke Development Server

We need to run the React development server, so start it using the suggested command.

npm start

React JS PHP Image Upload and Preview Example Tutorial

Conclusion

You must have gone through every step, assimilated preciously, and understood how easy it is to create the React PHP image uploader component.

Throughout this tutorial, we explained how to preview an image after uploading an image through a react form. Moreover, we demonstrated using PHP to save the uploaded image to the file system using the Axios package.