나중에 사용할 수 있도록 FileReader.readAsDataURL 결과를 (전역) 변수에 어떻게 할당합니까?FileReader 결과를 나중에 사용할 수 있도록 전역 변수에 할당하십시오.
FileReader.result가 asyc를 사용하며 reader.onload = function() {...}에서 사용할 수 있음을 알고 있지만 나중에 익명 콜백 내부의 전역 var에 할당 할 수 없었습니다. .
내가 봤 거든 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은 귀하가 결정한 것이 될 수 있습니다. –