我正在使用react-dropzone将文件上传到我的react应用程序中的服务器上。一切工作正常,但是我想添加一个功能,如果文件由于大小过长而无法上传,用户可以单击按钮取消该过程。
<Dropzone
multiple={ false }
accept={ allowedMimeTypes }
onDrop={ this.onDrop }
onDragEnter={ this.onDragEnter }
onDragLeave={ this.onDragLeave }
className={ classes.dropzone }
maxSize={ MAX_UPLOAD_BYTES }
>
</Dropzone>
<button onClick={ this.onCancelUpload }>Cancel</button>
如果可以使用react-dropzone,请告知。我想不出一种方法来停止已触发并正在上传文件的事件。
答案 0 :(得分:1)
我能够使用Axios Cancel Token解决以上问题。
const CancelToken = axios.CancelToken;
let source = CancelToken.source();
const {
acceptedFiles
} = this.state;
const uploaders = acceptedFiles.map((file) => {
const formData = new FormData();
// data must be set BEFORE sending file
formData.append('document', file);
const uploadConfig = {
onUploadProgress: (progressEvent) => {
const progressUpload = (progressEvent.loaded * 100) / progressEvent.total;
this.setState({
progressUpload
});
},
cancelToken: source.token,
};
return inkerzApi.post('/uploads/file', formData, uploadConfig)
.then(response => response.data)
.catch(() => console.log('Upload canceled'));
});
Promise.all(uploaders).then((filesMetadata) => {
filesMetadata.forEach((metadata) => {
if (metadata && metadata.mediaLink && metadata.totalPages) {
this.onNewFileUploaded(metadata);
// show success message here
} else if (this.state.uploadCanceled) {
// show cancelation notification here
this.setState({
uploadCanceled: false
});
}
});
this.setState({
acceptedFiles: [],
progressUpload: 0,
});
});
onCancelUpload = () => {
source.cancel('Operation canceled by the user.');
source = CancelToken.source();
this.setState({ uploadCanceled: true });
}
这对我有效。希望这对其他人也有帮助。