在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
|