2017-05-03 98 views
0

如何將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> 
+0

嘗試使用window.myGlobalVariable其中myGlobalVariable可以是您決定的任何內容。 –

回答

0

首先,你打錯this。在function的內部,this被動態綁定到調用函數的對象,如果它被稱爲方法。如果該函數未作爲方法調用,則thisundefined嚴格模式(模塊和類體隱含嚴格),否則它默認爲全局對象。

使用箭頭功能(params) => expression or block。箭頭功能靜態綁定this。在所有的函數中,除了這個以外,一切都是靜態綁定的在箭頭函數中,所有內容都是靜態綁定的。

export class AppComponent { 
    fileChangeEvent(fileInput: HTMLInputElement) { 

    reader.onload = e => { 
     const b64 = e.target.result 
     this.imageBase64 = b64; 

     preview.src = b64; 

     console.log(file); 
     console.log(b64); 
     window.IMAGE_RESULT = b64; 
    }; 
    } 
} 


declare global { 
    interface Window { 
    IMAGE_RESULT?: string; 
    } 
} 
+0

@mhoff在這個答案中修復了一些令人困惑的措辭。不要忘記爲它投票,如果它適合你:p –

+1

Aluan感謝您的解釋 - 正是我需要和它的工作。 (似乎我需要學習一些基本的打字稿) btw:實際上,我不得不將'e.target.result'改爲'reader.result' – mhoff

+0

@mhoff,它只是你需要學習的JavaScript。這是所有JS的東西 –

相關問題