theterminalguy

File Upload In React

March 01, 2017

It turns out that uploading file with react is pretty easy and not different from the way it’s done in plain JavaScript. Let’s do it now

class FileUploader extends React.Component {
  state = { file: null }
  handleFileChange = (e) => {
    this.setState({file: e.target.files[0]});
  }
  handleUpload = (e) => {
    e.preventDefault();
    const { file } = this.state;
    if(file) {
      console.log(file);
      const formData = new FormData();
      formData.append('file', this.state.file);
      //$.post("/path/to/server", formData);
    } else {
      //handle no file selected
    }
  }
  render(){
    return(
      <form>
        <input type="file" onChange={this.handleFileChange}/>
        <input type="submit" onClick={this.handleUpload} 
               value="Upload File" />
      </form>
      )
  }
}

You can now check the params on the server endpoint when an actual request is made to decide how you want the file to be handled. If you’re wondering where the FormData class came from, please see the docs on MDN

That is all. Feel free to configure it to your business needs. Thank you for reading.


Damian Simon Peter

Hi, I am Damian Simon Peter a software developer based in Waterloo, Ontario. I have spent the past years working for early-stage startups, building backend and frontend applications primarily using Ruby and JavaScript. I own a System76 Galago Pro running Pop!_OS and absolutely love it.