react upload file code example

Example 1: react image upload

/* Answer to: "react image upload" */

/*
  "react-images-upload" is a simple component for upload and
  validate (client side) images with preview built with React.js.
  This package use "react-flip-move [1]" for animate the file preview
  images.
  
  Download it here:
  https://www.npmjs.com/package/react-images-upload
  
  or if you need help or don't want to use packages,
  you can watch this video:
  https://www.youtube.com/watch?v=XeiOnkEI7XI

  [1] Link to "react-flip-move", mentioned in the 
  "react-images-upload" summary:
  https://github.com/joshwcomeau/react-flip-move
*/

Example 2: react upload file axios

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