【问题标题】:XMLHttpRequest Not StoppingXMLHttpRequest 没有停止
【发布时间】:2018-10-08 02:13:54
【问题描述】:

我有一个 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 时中止上传过程

【问题讨论】:

  • 我知道人们讨厌 cmets 建议使用库,但是在进行 ajax 调用时,我真的认为您应该使用某种抽象。 axios 还不错。

标签: javascript angular typescript xmlhttprequest angular6


【解决方案1】:

尝试使用 XMLHttpRequest 对象的 abort() 方法而不是 DONE。

像这样:

xhr.abort();

【讨论】:

    猜你喜欢
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多