Angular 中的图像/视频预览 [英] Image/Video Preview In Angular

查看:20
本文介绍了Angular 中的图像/视频预览的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Angular 上传图片或视频.我想显示它的预览.我在预览图像时没有问题,我的问题是如何预览视频?请参阅此 stackblitz 链接:

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:

点击此处


代码

 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;
      }
    }
  }

推荐答案

您可以决定文件是否为视频/图像类型,然后将其转发到合适的 html 控件

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;
    }
  }
}

更新的 Stackblitz:https://stackblitz.com/edit/angular-video-or-image-upload-preview-fjsukm

Updated Stackblitz: https://stackblitz.com/edit/angular-video-or-image-upload-preview-fjsukm

这篇关于Angular 中的图像/视频预览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆