Angular2-从输入文件读取二进制文件并将其绑定到对象 [英] Angular2 - read binary file from input file and bind it to object
问题描述
我已经获得了多个文件上传输入的文件二进制内容,这些输入已绑定到结构化对象的数组.
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);
}
我想要将文件的二进制内容绑定到对象的"binary"属性.
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屋!