3

使用 react-dropzone 上传文件,我想以文件传输百分比或 mbs 数据传输来实现文件进度。

这是链接: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>
4

3 回答 3

7

您可以使用React Dropzone Uploader,它为您提供开箱即用的上传进度的文件预览,并为您处理上传。

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/*"
    />
  )
}

可以取消或重新启动上传。UI 是完全可定制的。

完全披露:我编写这个库是为了解决React Dropzone所需的一些缺点和过多的样板。

于 2019-03-12T21:28:15.763 回答
4

如果您想检测文件上传过程,您可以使用 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*/
  };
}
于 2019-02-27T11:29:06.860 回答
1

这是基于 turchak 处理任意数量文件的答案的另一个示例:

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);
}
于 2020-06-02T12:21:22.483 回答