问题
I'm trying to upload image or video in Angular. I wanted to display its preview. I have no problem in previewing the image, my problem is how can i preview the video? Please see this stackblitz link:
CLICK HERE
CODE
onSelectFile(event) {
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.readAsDataURL(event.target.files[0]);
reader.onload = (event) => {
this.url = event.target.result;
}
}
}
回答1:
You can decide if the file is type of video/image and then forward it to suitable html controls
<img [src]="url" *ngIf="format==='image' && url" height="200"> <br/>
<video [src]="url" *ngIf="format==='video' && url" height="200" controls></video> <br/>
<input type='file' (change)="onSelectFile($event)" />
onSelectFile(event) {
const file = event.target.files && event.target.files[0];
if (file) {
var reader = new FileReader();
reader.readAsDataURL(file);
if(file.type.indexOf('image')> -1){
this.format = 'image';
} else if(file.type.indexOf('video')> -1){
this.format = 'video';
}
reader.onload = (event) => {
this.url = (<FileReader>event.target).result;
}
}
}
Updated Stackblitz: https://stackblitz.com/edit/angular-video-or-image-upload-preview-fjsukm
来源:https://stackoverflow.com/questions/58046879/image-video-preview-in-angular