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的东西 –

相关问题