how to show upload progress for each image upload

Viewed 5984

I am using react-dropzone for multiple image upload. The image upload is working but the upload progress is not showing. I could not find on the documentation clearly about showing upload progress. How can we show upload progress in react-dropzone?

I have created a codesandbox too. Here is the link

https://codesandbox.io/s/8BEmjLmo

Here is the code too

onDrop = (accepted, rejected) => {
    this.setState({
      accepted,
      rejected
    });
  };


  showFiles() {
    const { accepted } = this.state;
    return (
      <div>
        <h3>Dropped files: </h3>
        <ul className="gallery">
          {accepted.map((file, idx) => {
            return (
              <div className="col-md-3" key={idx}>
                <li>
                  <img
                    src={file.preview}
                    className="img-fluid img-responsive"
                    width={200}
                    alt={file.name}
                  />
                  <i
                    className="fa fa-remove"
                    onClick={e => this.handleRemove(file)}
                  />
                  <div className="imageName">{file.name}</div>
                </li>
              </div>
            );
          })}
        </ul>
      </div>
    );
  }
  render() {
    const { accepted } = this.state;
    return (
      <div style={styles}>
    <Hello name="CodeSandbox" />
    <Dropzone 
      onDrop={this.onDrop}
      style={style} 
      activeStyle={activeStyle}
      multiple
      accept="image/*"
    >
      Try Dropping file
        </Dropzone>
   {accepted.length !== 0 && this.showFiles()}
    </div>
    );
  }
}
2 Answers

Here is my full example that I use with react-dropzone:

onDrop(acceptedFiles) {
  const formData = new FormData();
  for (const file of acceptedFiles) formData.append('file', file);

  const xhr = new XMLHttpRequest();
  xhr.upload.onprogress = event => {
   const percentage = parseInt((event.loaded / event.total) * 100);
   console.log(percentage); // Update progress here
  };
  xhr.onreadystatechange = () => {
    if (xhr.readyState !== 4) return;
    if (xhr.status !== 200) {
     console.log('error'); // Handle error here
    }
     console.log('success'); // Handle success here
  };
  xhr.open('POST', 'https://httpbin.org/post', true);
  xhr.send(formData);
}
Related