File Upload In React

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) => {
  handleUpload = (e) => {
    const { file } = this.state;
    if(file) {
      const formData = new FormData();
      formData.append('file', this.state.file);
      //$.post("/path/to/server", formData);
    } else {
      //handle no file selected
        <input type="file" onChange={this.handleFileChange}/>
        <input type="submit" onClick={this.handleUpload} 
               value="Upload File" />

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.

Published 1 Mar 2017