как проверить размер файла ввода типа в реактивной форме - PullRequest
0 голосов
/ 15 января 2020

Я не получаю FileList для выбранного файла. Когда мы поддерживаем консоль event.target.files [0], он показывает undefined. Ожидаемый - если мы получим event.target.files [0], тогда мы сможем получить доступ к размеру файла.

HTMl

 <small *ngIf="FileUpload.errors?.fileSizeValidator" class="text-danger">File size is required</small>

fileSizeValidator.TS

import { AbstractControl, FormControl } from "@angular/forms";
export function fileSizeValidator(event: any) {
  return function(control: FormControl) {
    // return (control: AbstractControl): { [key: string]: any } | null => {
    const file = control.value;
    if (file) {
      //   var file_list = e.files.items(0);
      console.log(event.currentFiles + "eventttttttttttttttttttttt");
      var path = file.replace(/^.*[\\\/]/, "");
      const fileSize = FileList[0];

      const fileSizeInKB = Math.round(fileSize / 1024);

      if (fileSizeInKB >= 12) {
        return {
          requiredFileType: true
        };
      } else {
        return null;
      }
      return null;
    }
    return null;
  };
}

component.ts

this.addSlot
        .get("FileUpload")
        .setValidators([
          Validators.required,
          FileValidator.validate,
          fileSizeValidator(event),
          requiredFileType(["jpg", "png", "txt"])
        ]);

Ответы [ 3 ]

2 голосов
/ 20 января 2020

Решение

requireFileTypeValidator.ts

import { AbstractControl, FormControl } from "@angular/forms";
export function requiredFileType(type: string[]) {
  return function(control: FormControl) {
    // return (control: AbstractControl): { [key: string]: any } | null => {
    const file = control.value;
    const valid = null;
    var existValue: boolean = false;
    if (file) {

      var path = file.replace(/^.*[\\\/]/, "");

      const extension = path.split(".")[1].toUpperCase();
      for (var i = 0; i < type.length; i++) {
        let typeFile = type[i].toUpperCase();
        if (typeFile === extension.toUpperCase()) {
          existValue = true;
        }
      }
      if (existValue == true) {
        return null;
      } else {
        return {
          requiredFileType: true
        };
      }
      return null;
    }
    return null;
  };
}

fileSizeValidator.ts

    import { AbstractControl, FormControl } from "@angular/forms";
    export function fileSizeValidator(files: FileList) {
      return function(control: FormControl) {
        // return (control: AbstractControl): { [key: string]: any } | null => {
        const file = control.value;
        if (file) {
          var path = file.replace(/^.*[\\\/]/, "");
          const fileSize = files.item(0).size;
          const fileSizeInKB = Math.round(fileSize / 1024);
          if (fileSizeInKB >= 19) {
            return {
              fileSizeValidator: true
            };
          } else {
            return null;
          }
          return null;
        }
        return null;
      };
    }

Acomponent.ts

import { requiredFileType } from "../../../shared/requireFileTypeValidator";
import { fileSizeValidator } from "../../../shared/file-size.validator";

        export AComponent {
          UploadValue: boolean = false;
          fileChangeFunCalled: boolean = false;

         fileChange(files: FileList) {
            this.fileChangeFunCalled = true;
            if (this.uploadPanel == true && this.fileChangeFunCalled == true) {
              this.filesNum = { ...files };
              this.FileUpload.setValidators([
                Validators.required,
                requiredFileType(["jpg", "png", "txt"]),
                fileSizeValidator(files)
              ]);
              this.FileUpload.updateValueAndValidity();
              const fileSizeOrg = files.item(0).size;
              const fileSizeInKB = Math.round(fileSizeOrg / 1024);
              this.fileSize = fileSizeInKB;
              var extname = files.item(0).type;
              this.fileType = extname.split("/")[1].toUpperCase();
            }
          }
     handleFileInput() {
        this.uploadPanel = true;
        this.fileChangeFunCalled = false;
      }

 @HostListener("window:focus", ["$event"])
  onFocus(event: FocusEvent): void {
    if (this.uploadPanel == true && this.fileChangeFunCalled == false) {
      this.closePanel = true;
      this.addSlot
        .get("FileUpload")
        .setValidators([
          Validators.required,
          requiredFileType(["jpg", "png", "txt"])
        ]);
      this.addSlot.get("FileUpload").updateValueAndValidity();
    }
  }
        }

A Компонент. html

 <div class="form-group row" *ngIf="elemHideshow">
        <label
          for="FileUpload"
          class="label offset-sm-2 col-sm-2 col-form-label"
          >Upload Drop Mail :</label
        >
        <div class="col-sm-5">
          <input
            type="file"
            formControlName="FileUpload"
            [class.is-invalid]="FileUpload.invalid && uploadPanel"
            class="form-control"
            (change)="fileChange($event.target.files)"
            (click)="handleFileInput()"
            #inputTypeFile
          />
          <!-- {{ requiredFileType() }} -->
          <!-- <button onclick="document.getElementById('abc').click()">
            choose file
          </button> -->
          <div *ngIf="FileUpload.invalid && uploadPanel">
            <small *ngIf="FileUpload.errors?.required" class="text-danger"
              >File is required</small
            >
            <small
              *ngIf="FileUpload.errors?.requiredFileType"
              class="text-danger"
              >{{ fileType }} type is not allowed</small
            >
            <small
              *ngIf="FileUpload.errors?.fileSizeValidator"
              class="text-danger"
              >{{ fileSize }} KB size is not allowed.</small
            >
          </div>
        </div>
      </div>
0 голосов
/ 15 января 2020

Я так и сделал. функция экспорта fileSizeValidator (событие: {})

Но не получает FileList. не могли бы вы отредактировать приведенный выше код? Если я получу fileList, валидатор будет работать в реактивной форме.

0 голосов
/ 15 января 2020

Во-первых, вы должны удалить событие: любое в интерфейс [определить тип], если вы сделали бы это. Это дало бы вам представление о том, что происходит. Почему событие не определено.

event: {} //define the interface
...