在angular中实现图片/视频的预览

本文介绍如何在Angular应用中实现图片和视频的预览功能,包括相关组件的TS和HTML代码,但请注意,该实现缺少上传到服务器的逻辑,并且在某些情况下可能无法正确预览视频。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在angular中实现图片/视频的预览

需要预览功能的ts文件

import { Component, OnInit } from '@angular/core';


@Component({
  selector: 'app-test-upload-file',
  templateUrl: './test-upload-file.component.html',
  styleUrls: ['./test-upload-file.component.css']
})
export class TestUploadFileComponent implements OnInit {
  constructor() { }

  ngOnInit(): void {
  }
  //图片视频选择并预览
public imagePath:any;
imgURL: any;
videoURL: any;
fileChange(files:any) {
  // console.log(files.files);
//  console.log(files.files.length);
  if (files.files.length === 0) {
    return;
  }
  const reader = new FileReader();
  this.imagePath = files.files;
  
  if(files.files[0].type=='image/jpeg'){
    reader.readAsDataURL(files.files[0]);
    reader.onload = () => {
      this.imgURL = reader.result;
    };
  }

  if(files.files[0].type=='video/mp4'){
    reader.readAsDataURL(files.files[0]);
    reader.onload = () => {
      this.videoURL = reader.result;
    };
    }

该组件的html文件

<div>
    <input type="file" accept="image/*" (change)="fileChange($event.target)">
    <img *ngIf="imgURL" [src]="imgURL" >
  </div>
  
  <div>
    <input type="file" accept="video/*"  (change)="fileChange($event.target)">
  <video id="v1" autoplay loop muted>
  <source *ngIf="videoURL" [src]="videoURL" type="video/mp4">
  </video> 
  </div>

效果图:
在这里插入图片描述
存在的不足:
1.本代码没有上传到服务器的功能,需要自行添加。
2.上传视频时有时会出现不进行预览的问题。

参考的网站:https://segmentfault.com/a/1190000020169857

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值