Created
August 20, 2019 12:57
-
-
Save obenjiro/a381a8b7f4cf9d2ed4fb14b7c1952679 to your computer and use it in GitHub Desktop.
fileUploadService.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, OnDestroy } from '@angular/core'; | |
import { HttpClient, HttpEventType, HttpEvent } from '@angular/common/http'; | |
import { Subject, BehaviorSubject } from 'rxjs'; | |
import { switchMap, tap } from 'rxjs/operators'; | |
@Injectable({ providedIn: 'root' }) | |
export class FileUploadService implements OnDestroy { | |
public progress$ = new BehaviorSubject<Number>(0); | |
public loading$ = new BehaviorSubject<Boolean>(false); | |
private request$ = new Subject<[string, File[]]>(); | |
constructor( | |
private http: HttpClient | |
) { | |
this.request$.pipe( | |
tap(() => this.progress$.next(0)), | |
tap(() => this.loading$.next(false)), | |
switchMap(([url, files]) => this.http.post(url, this.toFormData(files), { | |
reportProgress: true, | |
observe: 'events' | |
})) | |
).subscribe(event => { | |
if (event.type === HttpEventType.UploadProgress) { | |
this.progress$.next(Math.round((100 * event.loaded) / event.total)); | |
} else if (event.type === HttpEventType.Response) { | |
this.progress$.next(100); | |
this.loading$.next(false); | |
} | |
}); | |
} | |
ngOnDestroy(): void { | |
this.request$.unsubscribe(); | |
} | |
public fileUploadCommand(url: string, files: File[]): void { | |
this.request$.next([url, files]) | |
} | |
private toFormData(files: File[]) { | |
const formData: FormData = new FormData(); | |
for (let i = 0; i < files.length; i++) { | |
formData.append('uploads[]', files[i], files[i].name); | |
} | |
return formData; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment