我有一个html动态表单,其中一个是公司下拉列表。如果 用户将从下拉列表中选择任何公司 表中特定公司的各个员工。 正在附加输入[文件]。现在,用户将上传每个的工资单 员工并保存数据。我的担心是将每行文件上传到 数据库放入不同的行。
component.html:
<table *ngIf="allemp">
<tr>
<th>ID</th>
<th>Name of Employee</th>
<th>Attached Payslip</th>
</tr>
<tr *ngFor="let data1 of allemp">
<td>{{data1.id}}</td>
<td>{{data1.emp_name}}</td>
<input formArrayName='payslip' type="file" (change)="onFileChangeInfo($event,i)" multiple></td>
</tr>
</table>
ts文件中多个更新的功能:
onFileChangeInfo(event,index) {
const reader = new FileReader();
var filesAmount = event.target.files.length;
this.items= this.myForm1.controls['payslip'] as FormArray;
console.log(this.items);
if(event.target.files && event.target.files.length > 0) {
const [files] = event.target.files;
this.regInfoName=event.target.files[0].name;
this.urlInfoUploadd= event.target.result;
for (let i = 0; i < filesAmount; i++) {
reader.readAsDataURL(event.target.files[i]);
reader.onload = () => {
this.urlInfoUpload = this.urlInfoUploadd;
this.regInfoNameHtml=this.regInfoName;
this.items.controls[index].patchValue({
'data_blob': reader.result,
'data_file':files.name,
});
console.log(files.name);
this.cd.markForCheck();
};
}
}
}
在console.log(filesAmount)上显示,它向我显示所有选定的文件。但是在数据库中只有最后一个文件。
我不明白我的代码有什么问题。请同样帮我。
答案 0 :(得分:0)
之前,我在ReactJS中也经历过类似的经历。因此,我将尽力重新编写我为您使用的代码。
您可以使用Promise.all()异步加载文件数组:
onFileChangeInfo(event) {
const files = Array.from(event.target.files); // Get files in array form
// Map each file to a promise that resolves an array of files
const promises = files.map(file => {
return (new Promise(resolve, reject) => {
const reader = new FileReader();
reader.addEventListener('load', (ev) => {
resolve(ev.target.result);
}
reader.addEventListener('error', reject);
reader.readAsDataURL(file);
}
});
// Once all promises are resolved, store the file blob in your variable
Promise.all(promises).then(files => {
this.items.controls.patchValue({
'data_blob': files
},
}, error => { console.error(error); });
}
我不知道您的代码看起来如何,所以我不知道您使用的是“ index”参数。但是,如果this.items.controls
是要在其中存储每个文件blob的数组,则不需要“索引”。