React 18 PHP 8 Upload and Store Base64 Image Tutorial

Last Updated on by in React JS

This React js PHP file upload tutorial will teach you how to upload and save base64 images in React js application using the Axios package and PHP programming language.

Furthermore, we will also help you learn how to handle file upload in react js in conjunction with HTML 5 multiple parts form data from scratch.

The multipart/form-data is one of the values of the enctype attribute that is utilized in form elements exclusively for file upload. In multipart, the form data is segmented into various parts and send to the server.

In this React js PHP base64 image upload example, you will see how to create a basic PHP backend server and use a PHP file to handle the POST request to upload a base64 image.

How to Upload and Store Base64 Image in React Js with PHP

  • Step 1: Download New React Project
  • Step 2: Set Up Bootstrap Library
  • Step 3: Add Axios Package
  • Step 4: Build File Upload Component
  • Step 5: Set Up Image Upload in PHP
  • Step 6: Register File Upload Component in App Js
  • Step 7: Start React App

Download New React Project

React offers a create-react-app method which is available through the terminal.

Now, you can prepend npx and execute the command followed by your project name to begin app installation.

npx create-react-app react-blog

Project has been downloaded, get into the app folder.

cd react-blog

Set Up Bootstrap Library

In the subsequent step, we will add the bootstrap package into the react js app. This library will allow creating of ui components swiftly.

npm install bootstrap --legacy-peer-deps

Further, we have to add the bootstrap CSS into the src/App.js and get authority to use bootstrap in react.

import React from 'react';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

 
function App() {
  return (
    <div>
      <h2>React Js Base64 Image Upload with PHP Example</h2>
    </div>
  );
}
 
export default App;

Add Axios Package

Next, we are installing the most significant package, allowing the HTTP request for handling form data in react.

npm install axios --legacy-peer-deps

Build File Upload Component

Now, to upload image to the server we have to create an image upload component, hence create src/components folder then create the ImageUpload.js file.

Upload src/components/ImageUpload.js file.

import React from 'react'
import axios from 'axios';

 
class ImageUpload extends React.Component{
 
    constructor(){
        super();
        this.state = {
            selectedImage: '',
        } 
        this.onFileChange = this.onFileChange.bind(this);
    }
 
    onFileChange(e) {
        let files = e.target.files;
        let fileReader = new FileReader();
        fileReader.readAsDataURL(files[0]);
 
        fileReader.onload = (event) => {
            this.setState({
                selectedImage: event.target.result,
            })
        }
    }
 
    onSubmit(){
        const formData = { image: this.state.selectedImage }
        let endpoint = "http://localhost:8888/backend.php";
         axios.post(endpoint, formData, {
         }).then((res) => {
            console.log('File uploaded!');
        })
    }
 
    render(){
        return(
            <div>
                <div className="form-group mb-3">
                    <label className="text-white">Select File</label>
                    <input type="file" className="form-control" name="image" onChange={this.onFileChange} />
                </div>

                
                <div className="d-grid">
                   <button type="submit" className="btn btn-outline-primary" onClick={()=>this.onSubmit()}>Store</button>
                </div>
                
            </div>
        )
    }
}
 
export default ImageUpload;

Set Up Image Upload in PHP

For this tutorial, we need a backend or server for storing the images through react frontend. First, create a backend.php file; after that, insert the given below code within the file.

<?php

    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST, PUT");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
     
    $DIR = "/var/www/react-php-upload/";

    $httpPost = file_get_contents("php://input");
    $req = json_decode($httpPost);
       
    $file_chunks = explode(";base64,", $req->image);
       
    $fileType = explode("image/", $file_chunks[0]);
    $image_type = $fileType[1];
    $base64Img = base64_decode($file_chunks[1]);
    
    $file = $DIR . uniqid() . '.png';
    file_put_contents($file, $base64Img); 
?>

Make sure to start the PHP server on your system; if you have installed php, you might take the help of the provided command.

php -S 127.0.0.1:8888

Register File Upload Component in App Js

Finally, we have to add the image upload component in the src/App.Js file, open the file and replace the existing code with the following code.

import React from 'react';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; 
import ImageUpload from './components/ImageUpload'


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

Start React App

The React multi-part file uploading feature has been built. Just one more thing, type command on the terminal and start the application.

npm start

React JS PHP Upload and Store Base64 Image Tutorial

Summary

In this React js multi-part form data tutorial, you have learned how to upload and store base64 image in React js application using the PHP programming language.

At the same time or conversely, we saw how to create a simple PHP backend and save the image in react through the multipart form data.