Skip to content

Instantly share code, notes, and snippets.

@whisher
Created March 22, 2019 19:56
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