如何将FileReader.readAsDataURL结果分配给(全局)变量以备后用?将FileReader结果分配给(全局)变量供以后使用
我知道FileReader.result的工作原理asyc并可以在reader.onload = function(){...}中使用但我无法将它分配给全局变量(从匿名回调中)供以后使用。
我google了一下,发现了一些提示也在stackoverflow,但没有什么真正帮助我。有什么建议么?
这里是我的代码:
app.component.ts:
export class AppComponent {
postData: PostData;
image: File;
status: string;
imageBase64: string
constructor(private http: Http) {
this.imageBase64 = '';
}
fileChangeEvent(fileInput: any) {
if (fileInput.target.files && fileInput.target.files[0]) {
let file = fileInput.target.files[0];
let preview = document.querySelector('img')
let reader = new FileReader();
this.image = file;
reader.onload = function (e: any) {
let b64 = e.target.result
// this.imageBase64 = b64; // undefinded here
preview.src = b64;
console.log(file);
console.log(b64);
}
reader.readAsDataURL(this.image);
}
}
uploadimage() {
// do something later with the bae64 reader.result - after upload button pressed
}
app.component.html:
所有的<label>Choose a file</label>
<input type="file" class="inputfile" accept="image/*"(change)="fileChangeEvent($event)">
<img id="preview" src="" height="200" alt="Image preview...">
<button (click)="uploadimage()">Upload Image</button>
尝试使用window.myGlobalVariable其中myGlobalVariable可以是您决定的任何内容。 –