这是在profile.component.html
中<label for="profile">Profile Photo</label>
<input type="file" [(ngModel)]='input'/>
<img [src]='input'>
这是在profile.component.ts
中profilePhoto: File;
set input(temp: File) {
this.profilePhoto = temp;
}
get input() {
return this.profilePhoto;
}
答案 0 :(得分:3)
首先,“文件输入”上的[(ngModel)]
实际上是提供一个字符串,而不是这里的File对象; set input(temp: File) { .. }
。
由于某些浏览器会保护文件路径,因此该字符串路径通常是虚拟的(即C:\ fakepath \ image.png)。有一些解决方法,但是这些方法在浏览器之间不一致。在这里看到更多关于这个的信息。 How to resolve the C:\fakepath?
某些浏览器具有一项安全功能,可阻止JavaScript 知道文件的本地完整路径。这很有意义-作为客户,您 不想让服务器知道您本地计算机的文件系统。它 如果所有浏览器都这么做的话,那将是很好的。
在您的情况下,您可以简单地使用FileReader加载Image元素的图像数据。这与您以后还要上传文件数据时可能使用的过程类似。
const fReader = new FileReader();
fReader.readAsDataURL(this.profilePhoto);
fReader.onloadend = (event) => {
this.profilePhotoImage = event.target.result;
}