将 FileReader 结果分配给(全局)变量供以后使用

assign FileReader result to a (global) variable for later use

如何将 FileReader.readAsDataURL 结果分配给(全局)变量供以后使用?

我知道 FileReader.result 异步工作并且可以在 reader.onload = function () {...} 中使用但我无法将它分配给全局变量(从匿名内部回调)供以后使用。

我用谷歌搜索并在 Whosebug 上也找到了一些提示,但没有任何帮助。有什么建议么?

这是我的代码:

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>

首先,你错了this。在 function 内部,this 动态绑定到调用该函数的对象(如果它作为方法调用)。如果函数不作为方法调用,this 在严格模式下是 undefined(模块和 class 主体是隐式严格的),否则它默认为全局对象。

this 也可以使用 Function.prototype.bind 绑定到特定对象。调用时,bind 返回的函数会将此解析为指定的对象。

function fullname() {
  return this.first + '_' this.last;
}

const philip = {first: 'Philip', last: 'Pullman'};
const philipsFullname = fullname.bind(philip);
console.log(philipsFullname()); // Philip Pullman

this 也可以在调用时设置,无需中间对象,使用 Function.prototype.call.

console.log(fullname.call(philip)); // Philip Pullman

使用箭头函数(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;
  }
}