【问题标题】:How to upload multipe files in angular and laravel with html table?如何使用 html 表上传 angular 和 laravel 中的多个文件?
【发布时间】:2019-09-29 18:30:18
【问题描述】:

我有一个 html 动态表单一个公司的下拉列表。如果 用户将从显示的下拉列表中选择任何公司 表中特定公司的各自员工。i 的每一行 我正在附加输入[文件]。现在用户将上传每个人的工资单 员工并保存数据。我关心的是把每行文件上传到 数据库到不同的行。

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) 上它显示了所有选定的文件。但在数据库中只有最后一个文件。

我不明白我的代码有什么问题。请帮助我。

【问题讨论】:

    标签: php laravel angular7 multiple-file-upload


    【解决方案1】:

    我之前在 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,那么你就不需要“索引”了。

    【讨论】:

      猜你喜欢
      • 2020-08-04
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-07
      • 2018-04-02
      • 2020-11-28
      • 1970-01-01
      • 2016-04-21
      相关资源
      最近更新 更多