Created
May 27, 2021 19:36
-
-
Save janpauldahlke/35047783dfedf10aef0616b03c8c68d2 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
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