Created
July 19, 2019 10:31
-
-
Save ngnam/89bd67d779b742529fff86bfbceb1d4a to your computer and use it in GitHub Desktop.
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 { 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