Upload and Store Base64 Image in React Js with PHP

Upload and Store Base64 Image in React Js with PHP

React js save base64 image example; In this tutorial, you will learn how to upload and store Base64 images in React Js with PHP. Base64 encoding is a way of encoding binary data in a format that is easily transmitted over the web. This can be useful when you want to send an image or other binary data over an HTTP request. React Js is a popular JavaScript library used for building user interfaces, while PHP is a server-side programming language used for web development.

And as well as, you’ll learn how to handle multi-part Form Data in React js app by implementing a simple file upload example using Axios and HTML5 FormData. For the backend, in this tutorial, you will learn in simple way to exposes a unique endpoint that accepts a POST request containing the file/image to upload base64 image in PHP.

Before you get started, it’s important to note that Base64 encoding is not the most efficient way to transmit images over the web. In fact, it can increase the size of the data being transmitted by about 33%. However, there are situations where it may be necessary to use Base64 encoding, such as when you need to store images in a database.

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

To upload and store base64 images in React JS, you need to follow the below steps:

  • Step 1 – Create React App
  • Step 2 – Install Axios and Bootstrap 4
  • Step 3 – Creating a React Js component for uploading images
  • 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>How to Upload Base64 Image in React Js</h2>
    </div>
  );
}

export default App;

Step 3 – Creating a React Js component for uploading images

In this step, visit the src directory of your react js app and create a image uplaod form component named FileUpload.js. And add the following code into it:

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

class FileUpload extends React.Component{

    constructor(){
        super();
        this.state = {
            selectedFile:'',
        }

        this.handleInputChange = this.handleInputChange.bind(this);
    }

    handleInputChange(event) {
        let files = event.target.files;
        let reader = new FileReader();
        reader.readAsDataURL(files[0]);

        reader.onload = (e) => {
            
            this.setState({
                selectedFile: e.target.result,
              })
        }

    }

    submit(){
        const formData = { image: this.state.selectedFile }
        
        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(){
        return(
            <div>
                <div className="row">
                    <div className="col-md-6 offset-md-3">
                        <br /><br />

                            <h3 className="text-white">React js Upload and Save Base64 Image - Tutsmake.com</h3>
                            <br />
                            <div className="form-row">
                                <div className="form-group col-md-6">
                                    <label className="text-white">Select File :</label>
                                    <input type="file" className="form-control" name="upload_file" onChange={this.handleInputChange} />
                                </div>
                            </div>

                            <div className="form-row">
                                <div className="col-md-6">
                                    <button type="submit" className="btn btn-dark" onClick={()=>;this.submit()}>Save</button>
                                </div>
                            </div>
                    </div>
                </div>
            </div>
        )  
    }
}

export default FileUpload;

In the aboe given code defines a React component called “FileUpload”. The component allows the user to select a file from their computer and submit it to a server using the Axios library.

The first two lines import the “React” and “axios” libraries. “React” is used to create and manage React components, while “axios” is used to make HTTP requests to a server.

The “FileUpload” class extends the “React.Component” class, indicating that it is a React component. It contains a constructor that initializes the component’s state with an empty “selectedFile” property.

The “handleInputChange” function is defined to handle changes to the file input field. It uses the FileReader API to read the selected file and set its value to the component’s state.

The “submit” function is called when the user clicks the “Save” button. It creates a FormData object containing the selected file and sends a POST request to the server using the Axios library.

Finally, the “render” function returns the HTML content of the component. It includes a file input field and a “Save” button that calls the “submit” function when clicked.

The “export default FileUpload” statement at the bottom of the file exports the “FileUpload” component so that it can be used in other parts of the application.

Step 4 – Add Component in App.js

In this step, you need to add FileUpload.js file in src/App.js file:

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import FileUpload from './FileUpload'

function App() {  
    
  return (  
    <div className="App">  
      <FileUpload/>  
    </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");
    
    $folderPath = "/var/www/upload-react/";
    $postdata = file_get_contents("php://input");
    $request = json_decode($postdata);
      
    $image_parts = explode(";base64,", $request->image);
      
    $image_type_aux = explode("image/", $image_parts[0]);
      
    $image_type = $image_type_aux[1];
      
    $image_base64 = base64_decode($image_parts[1]);
      
    $file = $folderPath . uniqid() . '.png';
      
    file_put_contents($file, $image_base64); 
  
?>  

The above given PHP code will perform the following steps:

  1. Set headers for Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers. These headers are used for Cross-Origin Resource Sharing (CORS) and allow resources on one domain to be accessed from another domain.
  2. Set the folder path where the uploaded image file will be stored.
  3. Get the input data from the HTTP request body using the file_get_contents() function and store it in the $postdata variable.
  4. Decode the JSON data using the json_decode() function and store it in the $request variable.
  5. Split the image data into two parts using the explode() function, where the separator is “;base64,”. The first part will contain the image type, and the second part will contain the base64-encoded image data.
  6. Split the image type from the first part by using another explode() function, where the separator is “image/”.
  7. Decode the base64-encoded image data using the base64_decode() function and store it in the $image_base64 variable.
  8. Generate a unique ID for the file name using the uniqid() function and concatenate it with the folder path and “.png” extension to create the complete file path and name.
  9. Write the decoded image data to the file using the file_put_contents() function.

Note that this code is designed to receive image data via a HTTP request and store it as a PNG file in a specified folder on the server. It assumes that the image data is sent as a JSON object with a base64-encoded image string named image.

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

React js save base64 image example. In this tutorial, you have learned how to upload base64 image and store in react js app. And as well as, you’ll learn how to handle multi-part Form Data in React js app by implementing a simple file upload example.

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 *