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>

3 Answers 3

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*/
  };
}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

How do you get the video previews? cannot find any reference in the docs :(
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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.