【问题标题】:Multiple file upload using custom directive in Angular在 Angular 中使用自定义指令上传多个文件
【发布时间】:2019-12-19 22:54:22
【问题描述】:

我正在尝试创建一个自定义指令来验证多个文件上传。但在自定义指令中,控件只是返回最后一个文件的详细信息而不是数组。

下面是代码:

文件上传.html:

<form [formGroup]="validateDocumentForm">
<input formControlName="document"  style="display: none" type="file" multiple (change)="onFileChanged($event)" #fileInput accept="application/pdf"  class="form-control">
<button class="btn upload-doc-btn" (click)="fileInput.click()"><span><i class="material-icons">vertical_align_top</i> Upload File</span></button>

文件上传.ts

ngOnInit() {
this.validateDocumentForm = this.formBuilder.group({
  document: this.formBuilder.array(['', [
    CustomValidator.uploadDocument
  ]]),
});

}

自定义验证器.ts:

export class CustomValidator {
    static uploadDocument(control: AbstractControl): 
    ValidationErrors | null {
      console.log(control); // only last file's details instead of 
                               array of selected files.
      console.log(control.value);
      return  null;
   }
}

【问题讨论】:

    标签: angular file-upload angular-reactive-forms directive custom-directive


    【解决方案1】:

    关于是否可以在单独的文件中实现 CustomValidator 的问题,我找到了本教程: https://dev.to/angular/implement-file-upload-with-firebase-storage-in-our-angular-app-the-simple-way-1ofi

    基本上,您将一个方法绑定为保存表单的组件内的验证器,这会在您的验证文件中调用一个单独的方法。

    我希望这个迟到的答案可以帮助某人。

    【讨论】:

      【解决方案2】:

      其实你不应该使用formArray来上传文件。如果您使用的是 formArray,则您在 html 文件中的循环中进行了迭代。(FormArray)

      ngOnInit() {
          this.validateDocumentForm = this.formBuilder.group({
              'document':[''] 
          })
      })
      

      选定的文件在value 中不可用,您必须使用目标中的files

      onFileChanged(event) {
          for (const x of event.target.files) {
              console.log(x);
              // do the validation here
          }
      }
      

      尝试在组件文件中而不是在 custom.validator 文件中进行验证

      编辑

      我们必须将文件存储在表单控件中,以便您可以在组件文件中执行类似的操作

      ngOnInit() {
          this.validateDocumentForm = this.formBuilder.group({
              'document':['', uploadDocument] 
          })
      })
      
      onFileChanged(event) {
          this.validateDocumentForm['controls']['document']['files'] = event.target.files;
      }
      

      在 custom.validators 文件中

      export function uploadDocument(c: AbstractControl) {
          console.log(c);
      if (c['target'] && 'files' in c['target']) {
          for (const x of c['target'].files) {
              if (/*do your condition*/) {
                  return {
                      'fileNotValid': true
                  };
              }
          }
       }
          return null;
      }
      

      【讨论】:

      • 感谢您的回答。 :) 有什么方法可以仅在 custom.validator 文件中管理验证,而不是使用组件文件?
      猜你喜欢
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 2016-06-22
      • 2015-10-06
      • 2019-10-18
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多