【问题标题】:how to show upload progress for each image upload如何显示每个图像上传的上传进度
【发布时间】:2017-11-01 05:03:19
【问题描述】:

我正在使用 react-dropzone 进行多张图片上传。图片上传正常,但没有显示上传进度。我无法在文档中清楚地找到有关显示上传进度的信息。我们如何在 react-dropzone 中显示上传进度?

我也创建了一个代码框。这是链接

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

这里也是代码

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>
    );
  }
}

【问题讨论】:

标签: javascript reactjs dropzone.js


【解决方案1】:

react-dropzone 中没有文件上传进度这样的功能。你得自己写,这里有一个例子:

const xhr = new XMLHttpRequest();

xhr.addEventListener("progress", function(e) {
  if (e.lengthComputable) {
    let percentComplete = e.loaded / e.total;
    console.log(percentComplete);
  }
});

// Just for demo.
xhr.open("POST", "/", true);
xhr.send(null);

另一种选择是使用React-Dropzone-Component

【讨论】:

  • 没有 xhr.我只有一个反应组件,只是将文件设置在内存中,稍后再发送
【解决方案2】:

这是我与 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);
}

【讨论】:

    猜你喜欢
    • 2017-12-06
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    相关资源
    最近更新 更多