Image/Video Preview In Angular

依然范特西╮ 提交于 2021-02-10 16:49:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!