React 17 Axios File Upload Example

React 17 file upoad form example; In this tutorial, i will show you in detail how to upload files with forms in react app.

Like you are implementing file upload form in any react app. And you want that with the help of this form the files should be stored in the database end server. So for this you have to send the multi-part HTML formdata to the server. For this, you will have to use PHP api with your react apps.

For react file upload example; i will create a simple form and upload files into database and directory of server. As well as, i will use php apis for sending and storing files data into server.

How to Upload Files in React Apps

  • Step 1 – Create React App
  • Step 2 – Install Axios and Bootstrap 4
  • Step 3 – Create File Upload Component
  • Step 4 – Import File Upload Component in App.js
  • Step 5 – Create PHP File

Step 1 – Create React App

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

Execute the following command on commenad prompt to install axios and bootstrap 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

Create file upload form component named FileUpload.js. So visit the src directory of your react app and create FileUpload.js component 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 - Laratutorials.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 – Import File Upload Component in App.js

Import FileUpload.js  component in App.js file; So visit the src/App.js file and import it, as shown below:

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

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

Execute the following command on command prompt to start the PHP server:

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 example; i have explained in detail how to upload file in react app using HTML formdata. And how to store images into database and directory using PHP endpoint rest apis.

React Posts

Leave a Comment