React JS Axios File Upload Example

React JS Axios File Upload Example

React js file upload with form data example; In this tutorial, you will learn how to upload file 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. Using Axios and HTML5 FormData.

Sometimes, you work in react js app and want to upload file in react js with php. So, in this example tutorial will learn step by step How to upload files in React Js with PHP.

For the backend, this tutorial will use a simple PHP application that exposes a unique endpoint that accepts a POST request containing the file/image to upload.

How to Upload Files in React Js App Example

Just follow the following steps and how to handle multi-part Form Data in React js app by implementing a simple file upload:

  • Step 1 – Create React App
  • Step 2 – Install Axios and Bootstrap 4
  • Step 3 – Create File Upload Form Component
  • 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>react file upload example</h2>
    </div>
  );
}

export default App;

Step 3 – Create File Upload Form Component

In this step, visit src directory of your react js app and create 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) {
        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 Example - 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;

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");
       
    // Folder Path For Ubuntu
    // $folderPath = "/var/www/my-app/uploads";
    // Folder Path For Window
    $folderPath = "uploads/";
   
    $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]);
?>

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 file upload form data example. In this tutorial, you have learned how to upload file in react js app. And as well as, you have learned how to handle multi-part Form Data in React js app by implementing a simple file upload example.

Recommended React JS Posts

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *