Skip to content

Instantly share code, notes, and snippets.

@janpauldahlke
Created May 27, 2021 19:36
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 janpauldahlke/35047783dfedf10aef0616b03c8c68d2 to your computer and use it in GitHub Desktop.
Save janpauldahlke/35047783dfedf10aef0616b03c8c68d2 to your computer and use it in GitHub Desktop.
onFileSelected(event: Event): void {
const file: File = (<HTMLInputElement>event.target).files[0];
this.fileName = file.name;
const { type } = file;
if (type === 'image/png' || type === 'image/jpg' || type === 'image/jpeg') {
// this is standart browser api
const formData = new FormData();
formData.append('thumbnail', file);
this.http.post(
'/api/thumbnail-upload',
formData,
// the magic behind upload progress revealed!
{
reportProgress: true,
observe: 'events',
}
)
.pipe(
catchError(error => {
this.fileUploadError = true;
//create observale
return of(error);
}),
//we want to unshow progress bar after upload
finalize(() => {
this.uploadProgress = null;
this.fileUploadError = false;
})
)
// here we will recieve the stream of events emmitted from the http-post
.subscribe(event => {
if (event.type === HttpEventType.UploadProgress) {
const { loaded, total } = event;
this.uploadProgress = Math.round((loaded / total) * 100);
}
if (event.type === HttpEventType.Response) {
this.onChange(this.fileName)
}
});
} else {
this.fileUploadError = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment