希望有人能教我一些新东西,我会尽量保持简短,因为我打赌这只是我希望错过的一些愚蠢的细节......
我从这样的图像开始,其中 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字符串,我看到currentImage
var字符串更新为html绑定(bind)中的base64字符串{{currentImage}}
,我看到 img
元素闪烁了新更新的图像...但随后它立即恢复到最初分配给 currentImage
的默认图像,即使 currentImage
仍然具有新的 base64 字符串....此外,this.currentImage
的最后一个 console.log
显示原始文件路径。
我一生都无法弄清楚为什么,但我对 FileReader、Angular 等 Web 端还是个新手。所以希望有人能给我快速提供一 block 简单的馅饼? :)
PS - 如果重要的话,它的 Angular 是 5
最佳答案
控制台日志中的
this.currentImage
首先执行,reader
中的 console.log 稍后执行。
你只是绑定(bind)了事件,然后告诉浏览器加载,同时浏览器加载图像并触发事件,最后的console.log已经被执行了。
更多代码或实例将有助于找出图像在首次加载后消失的原因。
关于html - 将文件输入 FileReader base64 结果动态分配给 IMG SRC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48220131/