如何解决Angular 9“无法在'FileReader'上执行'readAsDataURL':参数1的类型不是'Blob'”
当我尝试在上传图片之前显示所选图片时出现此问题
company.component.ts
handleFileInput(file: File){
console.log(file);
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = event => {
this.imageUrl = event.target.result;
console.log(this.imageUrl);
};
}
HTML
<input
type="file"
#fileInput
(change)="handleFileInput(fileInput.files[0])"
/>
<img [src]="imageUrl" height="50px" alt="">
解决方法
以下是如何实现的示例:
组件:
public imageUrl : SafeResourceUrl;
constructor(private sanitizer: DomSanitizer) { }
public upload(list: FileList): void {
const urlToBlob = window.URL.createObjectURL(list.item(0))
this.imageUrl = this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob);
}
模板:
<input type="file" (change)="upload($event.target.files)">
<img [src]="url">
,
尝试一下。
import { Component,OnInit,ChangeDetectorRef } from '@angular/core';
constructor(
private dtr: ChangeDetectorRef,){
}
handleFileInput(event) {
if (event.target.files && event.target.files[0]) {
this.imageFile = event.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(event.target.files[0]);
reader.onload = () => {
this.url = reader.result;
this.dtr.detectChanges();
};
}
在HTML文件中。
<input type="file" accept=".png,.jpg,.jpeg" (change)="handleFileInput($event)">
<img [src]="url">
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。