我能够使用Axios Cancel Token解决上述问题。
- 使用 Axios 将上传作为 Promise 处理。
- 在代码的开头创建一个源。
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 });
}
这对我有用。希望这对其他人也有帮助。