我有一个 XHR 来上传文件。用户可以单击按钮取消上传。
然后将 file.canceled
设置为 true
。我正在 onprogress
事件中检查上传是否已被取消。
如果它被取消,我会调用xhr.DONE
。但是,这根本不会停止上传过程。
代码(我使用的是 Angular 6,所以它是 Typescript)
upload(f: ProductFile): Observable<ProductFile> {
var file: ProductFile;
this.store$.pipe(
select(FilesSelectors.getFileById(f._id)),
).subscribe((file: ProductFile) => file = file)
return new Observable((observer) => {
let xhr = new XMLHttpRequest();
let progress: number = 0;
xhr.upload.onprogress = (event: ProgressEvent) => {
if (event.lengthComputable) {
progress = 100 * (event.loaded / event.total);
this.store$.dispatch(new FilesActions.UploadProgress({
...file, progress, uploaded: false, uploading: true,
}));
}
if (file.canceled) {
observer.error('canceled')
observer.complete();
xhr.DONE;
}
}
xhr.responseType = 'json';
xhr.open('POST', `${this.httpService.url}/files/upload`, true);
xhr.setRequestHeader('Authorization', this.httpService.token);
xhr.send(f.formData);
xhr.onload = () => {
const finishedFile: ProductFile = {
...f,
url: xhr.response,
uploaded: true,
uploading: false,
progress: 100,
};
observer.next(finishedFile);
observer.complete();
xhr.DONE;
}
});
}
所以我的目标是当file.canceled
等于true
时中止上传过程
最佳答案
尝试使用 XMLHttpRequest 对象的 abort() 方法而不是 DONE。
像这样:
xhr.abort();
关于javascript - XMLHttpRequest 没有停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52691401/