File upload progress using react-dropzone

Arun Arya picture Arun Arya · Feb 27, 2019 · Viewed 8.6k times · Source

Using react-dropzone to upload the file, I want to achieve the file progress like in percentage of file transfer or mbs data transfer.

Here is the link of: https://react-dropzone.netlify.com/

onDrop(acceptedFiles, uploadApi) {
  const filesToBeSent = this.state.filesToBeSent;
  if (acceptedFiles.length) {
    if (acceptedFiles[0].type === FileTypeList.TYPE) {
      filesToBeSent.push(acceptedFiles);
      const formData = new FormData();
      formData.append("file", acceptedFiles[0]);
      uploadApi(formData).then((response) => {
        this.setState({
          filesPreview: [],
          filesToBeSent: [{}],
          showNotification: true,
          uploadResponse: response,
        });
        this.props.fetchHistory();
      });
    } else {
      this.setState({
        fileType: true,
      });
    }
  } else {
    this.setState({
      fileSize: true,
    });
  }
}
<Dropzone maxSize={this.props.maxSize} onDrop={(files) => this.onDrop(files, this.props.uploadApi)}>
  {({ getRootProps, getInputProps }) => {
    return (
      <div {...getRootProps()} className={"dropzone"}>
        <UploadPanel id="uploadFileContainerId">
          <p>
            <img id="uploadImage" src={UploadImage} />
          </p>
          <input {...getInputProps()} />
          <div>{t("assets:UPLOAD_FILE")}</div>
          <Note>
            {this.props.maxSizeTitle ? t("workers:UPLOAD_WORKER_FILE_SIZE") : t("assets:UPLOAD_FILE_SIZE")}
          </Note>
        </UploadPanel>
      </div>
    );
  }}
</Dropzone>

Answer

kylebebak picture kylebebak · Mar 12, 2019

You can use React Dropzone Uploader, which gives you file previews with upload progress out of the box, and also handles uploads for you.

import 'react-dropzone-uploader/dist/styles.css'
import Dropzone from 'react-dropzone-uploader'

const Uploader = () => {  
  return (
    <Dropzone
      getUploadParams={() => ({ url: 'https://httpbin.org/post' })} // specify upload params and url for your files
      onChangeStatus={({ meta, file }, status) => { console.log(status, meta, file) }}
      onSubmit={(files) => { console.log(files.map(f => f.meta)) }}
      accept="image/*,audio/*,video/*"
    />
  )
}

Uploads can be cancelled or restarted. The UI is fully customizable.

Full disclosure: I wrote this library to address some of the shortcomings and excessive boilerplate required by React Dropzone.