首页 文章

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

提问于
浏览
2

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

场景是这样的:

我有一个这样的课:

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[] = [];

现在在组件中我已经实现了一个循环,以便组成一个表单,用户可以为每个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);
  }

我想要的是将文件的二进制内容绑定到对象的“二进制”属性 .

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

fileChange($event,t)

但是如果我扩展这个功能,它就不会受到打击......

我不知道怎么搬......

感谢支持

1 回答

  • 2

    将值添加到 fileChange 函数应该没问题 .

    我已经包含了一个显示它工作的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]);
      }
    

相关问题