Skip to content

Instantly share code, notes, and snippets.

@ngnam
Created July 19, 2019 10:31
Show Gist options
  • Save ngnam/89bd67d779b742529fff86bfbceb1d4a to your computer and use it in GitHub Desktop.
Save ngnam/89bd67d779b742529fff86bfbceb1d4a to your computer and use it in GitHub Desktop.
import { HttpClient, HttpEventType, HttpRequest } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable, of } from "rxjs";
@Injectable({ providedIn: "root" })
export class FileService {
constructor(private readonly http: HttpClient) { }
upload(files: FileList): Observable<number> {
if (files.length === 0) {
return of(0);
}
const formData = new FormData();
for (const file of files as any) {
formData.append(file.name, file);
}
const request = new HttpRequest("POST", "FileService/Upload", formData, { reportProgress: true, });
return new Observable((observable) => {
this.http.request(request).subscribe((event) => {
if (event.type === HttpEventType.Response) {
return observable.next(100);
}
if (event.type === HttpEventType.UploadProgress) {
return observable.next(Math.round(100 * event.loaded / event.total));
}
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment