File upload progress using react-dropzone
Asked Answered
N

3

5

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>
Newsdealer answered 27/2, 2019 at 10:38 Comment(0)
A
8

In case you wanna detect file upload process you can use XMLHttpRequest

onDrop(acceptedFiles) {
  const formData = new FormData();
  formData.append('file', acceptedFiles[0])

  const xhr = new XMLHttpRequest();
  xhr.open(/*params*/);
  xhr.send(formData)
  xhr.upload.onprogress = event => {
   const percentages = +((event.loaded / event.total) * 100).toFixed(2);
   this.setState({percentages})
  };
  xhr.onreadystatechange = () => {
    if (xhr.readyState !== 4) return;
    if (xhr.status !== 200) {
     /*handle error*/
    }
    /*handle success*/
  };
}
Achromic answered 27/2, 2019 at 11:29 Comment(0)
F
6

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.

Froward answered 12/3, 2019 at 21:28 Comment(1)
How do you get the video previews? cannot find any reference in the docs :(Goeselt
N
1

Here is another example based on turchak's answer for handling any number of files:

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);
}
Nomanomad answered 2/6, 2020 at 12:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.