Skip to content

Instantly share code, notes, and snippets.

@obenjiro
Created August 20, 2019 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save obenjiro/a381a8b7f4cf9d2ed4fb14b7c1952679 to your computer and use it in GitHub Desktop.
Save obenjiro/a381a8b7f4cf9d2ed4fb14b7c1952679 to your computer and use it in GitHub Desktop.
fileUploadService.ts
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