How to Save React Base64 Image in php ?

React.js

Nicesnippets

7894

06-03-2020


How to Save React Base64 Image in php ?

Hello Guys,

Now, let's see example of react image upload base64. you will learn react upload image to base64. you can understand a concept of how to save react base64 image in php. this example will help you upload image using react native.

In react upload image with axios first you have to install axios in your project. then we got one file input in form. after that on file input change you have to fire one function. in this function we set file object in state. then we fire api with axios on form submit button.

Install Axios Command


npm install axios --save

/src/App.js file

import React from 'react';

import './App.css';

import FileUpload from './FileUpload';

function App() {

return (

<div>

<FileUpload />

</div>

);

}

export default App;

/src/FileUpload.js file

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 Image Upload Base64 - Nicesnippets.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;

/upload-react/upload.php file

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);

?>

I hope it can help you...


Recommended Posts