3

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 Answer 1

13

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

3
  • 1
    Wish I found this yesterday -- would have saved me some time. Thanks!
    – AppDreamer
    Feb 9 at 17:55
  • I see it render a video player, but it's doesn't allow me to play, it's just black. I'm selecting a mov file using chrome in case that matters. Perhaps it's browser or file specific? May 18 at 12:17
  • If your browser can play video with native video tag then this should work. Nothing to do with the OP question :)
    – Joy Biswas
    May 18 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.