Angular2 - 从输入文件中读取二进制文件并将其绑定到对象 [英] Angular2 - read binary file from input file and bind it to object

查看:15
本文介绍了Angular2 - 从输入文件中读取二进制文件并将其绑定到对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have get the file binary content of multiple file upload inputs that are binded to an array of structured object.

场景是这样的:

我有一堂这样的课:

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 填充并用于组成表单:

Then I have my array that is filled by webapi and is used to compose the form:

public listFile: PriceList[] = [];

现在在组件中,我实现了一个循环,以便编写一个表单,用户可以在其中为每个 PriceList 项目选择要上传的文件:

Now in component I have implemented a loop in order to compose a form where the user can select the files to upload for each PriceList item:

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

用于管理二进制内容的ts函数:

ts function to manage the binary content:

  fileChange(e) {

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

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

What I want to to is bind the binary content of the files to the "binary" property of the object.

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

I need to pass the element to fileChange function, something like this:

fileChange($event,t)

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

But if I extend the function, it will not get hit...

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

I don't know how I have to move...

感谢支持

推荐答案

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

Adding the value to your fileChange function should be fine.

我已经包含了一个指向 StackBlitz 的链接,表明它可以正常工作.这里,使用 FileReader 将二进制文件读入 ArrayBuffer:

I've included a link to a StackBlitz that shows it working. Here, is uses FileReader to read the binary into an 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]);
  }

这篇关于Angular2 - 从输入文件中读取二进制文件并将其绑定到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆