article

Sunday, October 24, 2021

ReactJS Axios and PHP Mysql File Upload - Axios Post

ReactJS Axios and PHP Mysql File Upload - Axios Post

https://github.com/axios/axios

Installing the Axios Client
$ npm install axios

C:\reactdev\myreactdev>npm install axios

Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

C:\reactdev\myreactdev>npm install react-bootstrap bootstrap@5.1.3

https://react-bootstrap.github.io/getting-started/introduction/

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css'

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React from 'react';
import FileUploadForm  from "./FileUploadForm"

class App extends React.Component {
    render() {
        return (
            <FileUploadForm />
        );
    }
}
export default App;
src/FileUploadForm.js
//src/FileUploadForm.js
import React from 'react'
import axios from 'axios';

class FileUploadForm extends React.Component {

    UPLOAD_ENDPOINT = 'http://localhost/devtest/reactjs/upload.php';
    constructor(props) {
        super(props);
        this.state ={
          file:null
        }
        this.onSubmit = this.onSubmit.bind(this)
        this.onChange = this.onChange.bind(this)
        this.uploadFile = this.uploadFile.bind(this)
    }
    async onSubmit(e){
        e.preventDefault() 
        let res = await this.uploadFile(this.state.file);
        console.log(res.data);
    }
    onChange(e) {
        this.setState({file:e.target.files[0]})
    }
    async uploadFile(file){
        const formData = new FormData();
        formData.append('avatar',file)
        return  await axios.post(this.UPLOAD_ENDPOINT, formData,{
            headers: {
                'content-type': 'multipart/form-data'
            }
        });
    }
    
      render() {
        return (
          <div className="container" style={{padding: 20}}>
            <h1> ReactJS Axios and PHP Mysql File Upload - Axios Post </h1>
            <div className="row">
            <form onSubmit={ this.onSubmit } className="form-inline">
                <div className="form-group">
                <label>Choose File to Upload: </label>
                <input type="file" className="form-control" onChange={ this.onChange } />
                </div> <br/>
                <button type="submit" className="btn btn-success" >Upload File</button>
            </form>
          </div>
          </div>
       )
      } 
}
export default FileUploadForm;
http://localhost/devtest/reactjs/upload.php
//http://localhost/devtest/reactjs/upload.php
<?php 
header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");

$response = array();
$upload_dir = 'uploads/';
$server_url = 'http://localhost/devtest/reactjs/';

if($_FILES['avatar'])
{
    $avatar_name = $_FILES["avatar"]["name"];
    $avatar_tmp_name = $_FILES["avatar"]["tmp_name"];
    $error = $_FILES["avatar"]["error"];

    if($error > 0){
        $response = array(
            "status" => "error",
            "error" => true,
            "message" => "Error uploading the file!"
        );
    }else 
    {
        $random_name = rand(1000,1000000)."-".$avatar_name;
        $upload_name = $upload_dir.strtolower($random_name);
        $upload_name = preg_replace('/\s+/', '-', $upload_name);
    
        if(move_uploaded_file($avatar_tmp_name , $upload_name)) {
            $response = array(
                "status" => "success",
                "error" => false,
                "message" => "File uploaded successfully",
                "url" => $server_url."/".$upload_name
              );
              
            $host = "localhost"; 
            $user = "root"; 
            $password = ""; 
            $dbname = "testingdb"; 
              
            $con = mysqli_connect($host, $user, $password,$dbname);  

            if (!$con) {
                die("Connection failed: " . mysqli_connect_error());
            }

            $sql = "insert into users (username, name, photo) values ('cairocoders', 'cairocoders Ednalan', '$upload_name')"; 
            mysqli_query($con,$sql);
        }else
        {
            $response = array(
                "status" => "error",
                "error" => true,
                "message" => "Error uploading the file!"
            );
        }
    }

}else{
    $response = array(
        "status" => "error",
        "error" => true,
        "message" => "No file was sent!"
    );
}

echo json_encode($response);
?>

Related Post