如何避免在 Angular 中上传大视频?

问题描述

我有一个 Angular 应用程序,可让您上传图像和视频。但是,我想避免上传超过 30 秒的视频。我的问题是...考虑以下 StackBlitz 如何防止加载时长超过 30 秒的视频?而不是在加载和显示删除它们?是否可以使用 Angular 实现这一目标?

非常感谢!

解决方法

是的,有可能

这个想法是创建一个对象 url,并将其加载到视频元素中,这允许在将其上传到服务器之前获取视频的属性:

模板:

<video #vid controls width="500px" id="vid" style="display:none"></video>

组件:

@ViewChild("vid") ele: any;
onSelectFile(event) {
  const files = event.target.files;
  if (files) {
    for (const file of files) {
      const objectUrl = URL.createObjectURL(file);
      this.ele.nativeElement.src = objectUrl;
      const reader = new FileReader();
      reader.onload = (e: any) => {
        if (this.ele.nativeElement.duration > 30) {
            alert("movie is too long!");
        }
        this.mydata.push({
            url: e.target.result,type: "video"
        });
      }
    };
    reader.readAsDataURL(file);
  }
}

这是一个working stackblitz