【问题标题】:Angular2 - read binary file from input file and bind it to objectAngular2 - 从输入文件中读取二进制文件并将其绑定到对象
【发布时间】:2018-05-08 00:45:19
【问题描述】:

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

场景是这样的:

我有这样的课:

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)

但是如果我扩展这个功能,它就不会被命中...

我不知道我必须如何移动......

感谢支持

【问题讨论】:

    标签: angular angular2-forms


    【解决方案1】:

    将值添加到您的 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]);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-25
      • 2023-03-23
      • 2014-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多