检查上传的视频长度-Angular

时间:2018-10-10 12:37:30

标签: javascript angular

我正在尝试检查上传的视频是否长于30秒,但无法获取所需的示例。到目前为止,这是我检查尺寸和其他一些东西的代码:

readVideoUrl(event: any) {
      this.videoFile = [];
        const eventObj: MSInputMethodContext = <MSInputMethodContext> event;
        const target: HTMLInputElement = <HTMLInputElement> eventObj.target;
        const files: FileList = target.files;
        if (files) {
            this.videoFile.push(files[0]);
            this.videoModel.name = files[0].name;
        }


        if (event.target.files && event.target.files[0]) {
            let reader = new FileReader();

            reader.onload = (event: ProgressEvent) => {
                this.videoUrl = (<FileReader>event.target).result;
            };

            reader.readAsDataURL(event.target.files[0]);
        }

        const FileSize = files[0].size / 1024 / 1024; // in MB
        if (FileSize > 50) {
            this.videoSizeError = true;
        } else {
            this.videoSizeError = false;
        }

        this.videoModel.file = event.target.value;
        this.videoModel.name = event.target.files[0].name;
    }

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

我将添加一个不可见的视频播放器并设置其来源,然后从中获取持续时间:

HTML:

<input type="file" (change)="readVideoUrl($event)">

<p *ngIf="videoSizeError">Too big</p>

<video #video style="display: none;" *ngIf="videoUrl" width="320" height="240" controls [attr.src]="videoUrl" (loadedmetadata)="getDuration($event)">
</video>

TS:

import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  videoUrl;
  videoSizeError;

  constructor(private sanitizer: DomSanitizer) { }

  readVideoUrl(event: any) {
    const files = event.target.files;
    if (files && files[0]) {
      this.videoUrl = this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(files[0]));
    }
  }

  getDuration(e) {
    const duration = e.target.duration;
    this.videoSizeError = duration > 30;
  }
}

working code's link