Created
March 22, 2019 19:56
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
Credit to https://gist.github.com/iansinnott/3d0ba1e9edc3e6967bc51da7020926b0 | |
export class UploadComponent { | |
@ViewChild('file') file: ElementRef; | |
imagePreview$: Observable<ArrayBuffer | string>; | |
onFile(event) { | |
event.preventDefault(); | |
event.stopPropagation(); | |
this.file.nativeElement.click(); | |
} | |
onImageUpload(event: Event) { | |
const file = (<HTMLInputElement>event.target).files[0]; | |
this.imagePreview$ = this.fileReaderObs(file); | |
} | |
fileReaderObs(blob: Blob): Observable<string> { | |
return Observable.create(obs => { | |
if (!(blob instanceof Blob)) { | |
obs.error(new Error('`blob` must be an instance of File or Blob.')); | |
return; | |
} | |
const reader = new FileReader(); | |
reader.onerror = err => obs.error(err); | |
reader.onabort = err => obs.error(err); | |
reader.onload = () => obs.next(reader.result); | |
reader.onloadend = () => obs.complete(); | |
return reader.readAsDataURL(blob); | |
}); | |
} | |
} | |
<div fxLayout="column"> | |
<div *ngIf="(imagePreview$ | async) as imagePreview"> | |
<img class="img-fluid" [src]="imagePreview" [alt]="" /> | |
</div> | |
<div fxLayout> | |
<button fxFlex mat-flat-button color="accent" (click)="onFile($event)"> | |
<mat-icon>cloud_upload</mat-icon> | |
</button> | |
<input type="file" #file (change)="onImageUpload($event)" /> | |
</div> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment