ReactJs File uploading Example with Axios

  372 views   4 months ago React

This tutorial will provide an example of react js file upload component. you can understand the concept of react js file upload to server. you can optically discern react js upload a file. This post will give you a simple example of react js ajax file upload. Follow the below tutorial step of reactjs file upload formdata.

In react upload image with Axios first you have to install Axios in your project. then we got one file input in a form. after that on file input transmute you have to fire one function. in this function, we set the file object in the state. then we fire API with Axios on the form submit button.

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) {
        this.setState({
            selectedFile: event.target.files[0],
          })
    }

    submit(){
        const data = new FormData() 
        data.append('file', this.state.selectedFile)
        console.warn(this.state.selectedFile);
        let url = "http://localhost:8000/upload.php";

        axios.post(url, data, { // receive two parameter endpoint url ,form data 
        })
        .then(res => { // then print response status
            console.warn(res);
        })

    }

    render(){
        return(
            <div>
                <div className="row">
                    <div className="col-md-6 offset-md-3">
                        <br /><br />

                            <h3 className="text-white">React File Upload - HackTheStuff</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");
       
// Folder Path For Ubuntu
// $folderPath = "/var/www/upload-react/";
// Folder Path For Window
$folderPath = "upload-react/";
   
$file_tmp = $_FILES['file']['tmp_name'];
$file_ext = strtolower(end(explode('.',$_FILES['file']['name'])));
$file = $folderPath . uniqid() . '.'.$file_ext;
move_uploaded_file($file_tmp, $file);
   
return json_encode(['status'=>true]);

I hope it can help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]