我正在使用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>
);
}
}
答案 0 :(得分:1)
这是我与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);
}
答案 1 :(得分:0)
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