Angular2 - 从输入文件读取二进制文件并将其绑定到对象

Angular2 - read binary file from input file and bind it to object

我已获取绑定到结构化对象数组的多个文件上传输入的文件二进制内容。

场景是这样的:

我有一个 class 这样的:

export class PriceList {
    public idPriceList: number;
    public code: string;
    public name: string;
    public binary: any;//this property has to contain the binary content of the selected file
}

然后我有一个由 webapi 填充并用于组成表单的数组:

public listFile: PriceList[] = [];

现在在组件中我已经实现了一个循环以组成一个表单,用户可以在其中 select 为每个 PriceList 项目上传文件:

<ng-contrainer *ngFor="let t of listFile">
<tr>
    {{t.code}}<input type="file" id="ImageBinary" (change)="fileChange($event)">
</tr>
</ng-container>

ts函数管理二进制内容:

  fileChange(e) {

    var file = e.target.files[0];
    .......
    console.log(e);
  }

我想要的是将文件的二进制内容绑定到对象的 "binary" 属性。

我需要将元素传递给 fileChange 函数,如下所示:

fileChange($event,t)

但是如果我扩展函数,它就不会被击中...

我不知道我要怎么移动...

感谢支持

将值添加到您的 fileChange 函数应该没问题。

我已将 link 添加到 StackBlitz 中,表明它可以正常工作。这里,是使用 FileReader 将二进制文件读入 ArrayBuffer:

https://stackblitz.com/edit/angular-meo6yz

<input type="file" id="ImageBinary" (change)="fileChange($event, t)">
  fileChange(event, item) {
    item.binary = event;
    var r = new FileReader();
    r.onload = function(e) { 
      item.binary = r.result
    }
    r.readAsArrayBuffer(event.target.files[0]);
  }