使用自定义验证器验证多个文件

时间:2019-08-19 04:02:40

标签: angular file customvalidator angular-validation

我想验证多个文件以确保它们是特定类型。我正在使用Angular自定义验证器来做到这一点。我已使用以下方法成功验证了单个文件。但我想验证多个文件。 请推荐使用此方法或其他任何可行方法的解决方案。 TIA

mime-type.validator.ts

imports     
export const mimeType = (control: AbstractControl): Promise<{ [key: string]: any }> | Observable<{ [key: string]: any }> => {
    console.log(control.value)
    const file = control.value;
    const fileReader = new FileReader();
    const fileReaderObservable: Observable<{ [key: string]: any }> = Observable.create((observer: Observer<{ [key: string]: any }>) => {
        fileReader.addEventListener('loadend', () => {
            const array = new Uint8Array(fileReader.result as ArrayBuffer).subarray(0, 4);
            let header = "";
            let isValid = false;
            for (let i = 0; i < array.length; i++) {
                header += array[i].toString(16);
            }
            switch (header) {
                case "89504e47":
                    isValid = true;
                    break;
                case "ffd8ffe0":
                case "ffd8ffe1":
                case "ffd8ffe2":
                case "ffd8ffe3":
                case "ffd8ffe8":
                    isValid = true;
                    break;
                default:
                    isValid = false;
                    break;
            }
            if (isValid) {
                observer.next(null);
            }
            else {
                observer.next({ inValidMimeType: true });
            }
            observer.complete();
        });
        fileReader.readAsArrayBuffer(file as Blob);
    })
    return fileReaderObservable;
}

component.ts文件

onFileSelected(event: Event) {
    const element = document.getElementById('file-list');
    this.renderer.addClass(element, 'selected-file-list')
    const files = (event.target as HTMLInputElement).files[0];
    this.newRecordForm.patchValue({ files: files });
    this.newRecordForm.get('files').updateValueAndValidity();
  }

模板文件

<div *ngIf="fileSelection === 'file'">
              <div class="upload-title">Upload file</div>
              <button type="button" mat-button (click)="browseFile.click()">Browse</button>
              <input type="file" (change)="onFileSelected($event)" #browseFile multiple>
            </div>

0 个答案:

没有答案