Javascript 通过输入:file接受后,如何在新选项卡中预览任何类型的文件?
通过Javascript 通过输入:file接受后,如何在新选项卡中预览任何类型的文件?,javascript,angular,typescript,file-upload,angular9,Javascript,Angular,Typescript,File Upload,Angular9,通过input:file接受后,我想在新选项卡中显示所选文件。但问题是文件没有预览。我遵循了这一点,但没有得到结果。 下面是我的代码: app.component.html <button mat-button (click)="file1.click()" style="margin-bottom: 5px;"> Attach File </button> <input type="file" sty
input:file
接受后,我想在新选项卡中显示所选文件。但问题是文件没有预览。我遵循了这一点,但没有得到结果。
下面是我的代码:
app.component.html
<button mat-button (click)="file1.click()" style="margin-bottom: 5px;">
Attach File
</button>
<input type="file" style="display: none;" id="file1" #file1 (change)="preview($event)" />
<a [href]="url" target="_blank" #previewFile>
<mat-chip *ngFor="let file of fileArray" class="chips">
{{ file.fileName }}
</mat-chip>
</a>
附加文件
应用程序组件.ts
url: any;
@ViewChild('previewFile') previewFile: ElementRef<HTMLInputElement>;
preview(event: Event) {
const file = (event.target as HTMLInputElement).files[0];
if (!file)
return;
this.fileArray.push({
fileName: file.name
});
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = event => {
this.url = (<FileReader>event.target).result;
this.previewFile.nativeElement.setAttribute('href', this.url);
};
}
url:any;
@ViewChild('previewFile')previewFile:ElementRef;
预览(事件:事件){
常量文件=(event.target作为HTMLInputElement).files[0];
如果(!文件)
返回;
此文件名为.fileArray.push({
文件名:file.name
});
const reader=new FileReader();
reader.readAsDataURL(文件);
reader.onload=事件=>{
this.url=(event.target).result;
this.previewFile.nativeElement.setAttribute('href',this.url);
};
}
我的文件有不同的类型,如PDF、DOC、EXCEL、图像、视频。
请帮我解决这个问题