繁体   English   中英

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

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

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

我知道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>

首先,您this有误。 内的functionthis被动态地绑定到在其上调用函数时,如果它被称为方法的对象。 如果该函数不调用为方法, thisundefined在严格模式(模块和类机构是隐式地严格)和否则默认为全局对象。

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;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM