Friends, we will learn in this tutorial how to upload and store Base64 Image in React JS application. We will use the Axios package and PHP Programming Language.
In addition, we will get to learn to handle file uploading in react js in conjunction with HTML 5 multiple parts from the data.
The multipart/form-data is one of the values of enctype attribute that is used in form elements exclusively for the file upload. In multipart, the data is further segmented into various parts for sending to the server.
We will learn 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
See below to learn the step by step implementation of the above-mentioned:
Step 1- Download The New React Project
React offers a create-react-app method which is available through the terminal.
Now, we can prepend npx and execute the command followed by the project name to begin the app installation.
npx create-react-app react-upload-demo
Since we have downloaded the project, we get into the app folder.
cd react-upload-demo
Step 2- Setup The Bootstrap Library
Afterwards, we add the bootstrap package into the react js app. With the help of this library, the creation of UI components becomes swift.
npm install bootstrap
Then, we add the bootstrap CSS into the src/App.js and get the 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;
Step 3- Add Axios Package
The next step is to install the most significant package, allowing the HTTP request for handling form data in react.
npm install axios
Step 4- Build File Upload Component
The fourth step is to create an image upload component for uploading the image to the server. So, we create src/components folder. Then, we create 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;
Step 5- Set Up Image Upload In PHP
For implementing this example, for storing the images react frontend, we need a backend or server. So, firstly we create backend.php file and after that, we insert the given 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);
?>
Do remember to start the PHP server on the system. After installing php, we can take the help of the given command.
php -S 127.0.0.1:8888
Step 6- Register File Upload Component In App JS
Afterwards, we have to add the image upload component in the src/App.Js file. Open the file and replace the existing code with the below-given 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;
Step 7- Start the React App
The React multi-part file uploading has been taught throughout this tutorial. Lastly, we type the given command on the terminal to start the application.
npm start
Conclusion
So, we hope that you have completely learned to upload and store Base64 Image in React JS application using the Axios package and PHP Programming Language.
Also, we have seen how to create a simple PHP backend and save the image in react through the multipart form data.
Thanks