Cancellable Multiple File Upload Progress using forkJoin
Requirement: Show progress status for multiple files being uploaded to their own reserved upload url (provided by OpenStack — an object storage system) and allow to cancel upload.
In this scenario, first a container url and a share uuid (specific for this multiple upload) must be obtained via an api. After that, it is now possible to obtain upload urls per file (associated with that share uuid) via another api.
Firstly, we need to pass the options below to the PUT api we will be calling for file upload:
reportProgress: true,
observe: 'events'
With “reportProgress: true’”, we can now observe events (types can be “Sent” — started, “UploadProgress/DownloadProgress” — in progress, “Response” — uploaded). You can visit Angular’s official docs for more detail.
forkJoin accepts a variable number of observables and subscribes to them in parallel. When all of the provided Observables are complete, forkJoin collects the last emitted value from each and emits them as an array. It has a similar behavior with Promise.all but for Observables.
- The method to get container url => getSharingLink
- The method to get file specific urls => getUploadLinks
All API call subscriptions are assigned to a Subscription to be able to cancel if the user clicks to cancel upload at any phase.
Here is the implementation:
When the user clicks Cancel, we will cancel all subscriptions and cancel file uploads if started (isUploadFailure is a flag I use to show upload progress bar full with red color if upload is cancelled by the user or an error occurs).
cancelUpload(): void {
if (this.sharingSubscription) {
this.sharingSubscription.unsubscribe();
}
if (this.uploadSubscription) {
this.uploadSubscription.unsubscribe();
}
if (this.forkJoinSubscription) {
this.forkJoinSubscription.unsubscribe();
}
this.isUploadFailure = true;
}
Happy Coding!