【发布时间】:2018-01-12 05:32:44
【问题描述】:
希望有人能教我一些新的东西,我会尽量保持简短,因为我打赌这只是我希望错过的一些空洞的细节......
我从这样的图像开始,其中currentImage 是一个现有的图像路径,首先作为默认值;
<img src="{{currentImage}}">
<input type="file" (click)="onUpload($event)">
然后触发一个基本方法来获取 event.files 等;
onUpload(event) {
const file: File = event.files[0],
reader: FileReader = new FileReader(),
that = this; // *** WORTH NOTING...
reader.addEventListener('loadend', function () {
console.log('the resulting base64 string = ', reader.result);
that.currentImage = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
console.log('does the blob get updated to currentimage?',
this.currentImage); // THIS RETURNS THE OLD IMAGE PATH***
}
这种工作,我在控制台看到我想要的base64字符串,我看到currentImagevar字符串更新到html绑定{{currentImage}}中的base64字符串,我看到img元素闪烁新更新的图像...但随后它立即恢复为最初分配给currentImage 的默认图像,即使currentImage 仍然具有新的base64 字符串...。this.currentImage 的最后一个console.log 显示原始文件路径。
我一生都想不通为什么,但我是使用 FileReader、Angular 等 Web 端的新手。所以希望有人可以快速为我提供一块不起眼的馅饼? :)
PS - 如果重要的话,它是 5 角
【问题讨论】:
-
请看下面我的回答,这首先不是一个公平的问题。干杯!
标签: html angular typescript filereader