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;
      }
    }
  }
                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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With