One of the functionalities in my app involves uploading files using XHR. Users have the option to cancel the upload by clicking on a button.
If the user cancels the upload, the value of file.canceled
is set to true
. I'm constantly checking during the upload progress (onprogress
event) to see if the upload has been canceled.
In case of cancellation, I trigger xhr.DONE
. However, this action does not actually stop the upload process as intended.
Here's the code snippet: (I'm working with Angular 6 and using 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;
}
});
}
My main objective is to properly abort the uploading process when the value of file.canceled
is indeed true
.