Как настроить проверку типа файла ввода изображения - PullRequest
0 голосов
/ 09 января 2019

привет. Я хочу проверить входной файл html type image, просто примите 'png', 'jpg', 'jpeg', 'gif' и не превышайте 2 МБ, пока я не смогу сделать возможным только то, что он не займет у меня this.firstFormGroup.controls.image .status, если вы введете любой другой файл активирован как действительный статус.

 handleFileInput(event) {

  const file = event.target.files[0];
  const typeFile = file.type.split('/');
  const filemb: number = file.size / 1000000;
  if (filemb <= 2 && (typeFile[1] === 'png' || typeFile[1] === 'jpg' || typeFile[1] === 'jpeg' || typeFile[1] === 'gif') ) {
        const filePath = `${this.rutaImg}/${file.name}`;
        const fileRef = this.storage.ref(filePath);
        const task = this.storage.upload(filePath, file);
        this.uploadPercent = task.percentageChanges();
        task.snapshotChanges().pipe(
            finalize(() => {
              this.downloadURL = fileRef.getDownloadURL();
              this.downloadURL.subscribe( url => {
                if ( url ) {
                  this.urlImg = url;
                  console.log(this.urlImg);
                  this.validateImage = true;
                  console.log(this.validateImage );
                  return {
                    isError: this.validateImage
                };
                }
             });
            })
         )
        .subscribe();

  } else {
    this.validateImage = false;
  }
}

HTML-код

    <div>
        <input formControlName="image"  (change)="handleFileInput($event)" type="file"  id="file" class="inputfile" accept="image/*"  required/>
        <label for="file"><mdb-icon icon="camera"></mdb-icon> Insertar Imagen &nbsp;
          <progress  style="margin-top: -10px; " *ngIf="uploadPercent" max="100" [value]="(uploadPercent | async)"></progress>
       </label>
 </div>

FormGroup

this.firstFormGroup = this.fb.group({
      ruc: ['', rucValidator],
      razon_social: ['', nameValidator],
      nameBussines: ['', nameValidator],
      phone: ['', phoneValidator],
      describe: ['', describeValidator],
      plan: ['', Validators.required],
      category: ['', Validators.required],
      image: ['', this.validateImage]
    });

1 Ответ

0 голосов
/ 14 января 2019

Вам нужно создать пользовательский FormControl, я покажу вам, как его создать ( онлайн-пример ) или вы можете использовать модуль npm ( FileInputAccessor )


Шаги для создания FormControl и загрузки действительного файла

  1. Реализует ControlValueAccessor
  2. Добавлены пользовательские правила проверки
    • Регистрация для пользовательских правил проверки
  3. Слушайте изменения событий в ваших реактивных формах
    • Загрузить действительный файл в ваше хранилище

1.Implements ControlValueAccessor

изображения formcontrol.component

import { Component, OnInit, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { ImageFormcontrol } from './image-formcontrol';
@Component({
  selector: 'app-image-formcontrol',
  templateUrl: './image-formcontrol.component.html',
  styleUrls: ['./image-formcontrol.component.css'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => ImageFormcontrolComponent),
      multi: true
    }
  ]
})
export class ImageFormcontrolComponent implements OnInit, ControlValueAccessor {

  _registerOnChangeFn;
  _registerOnTouchedFn;

  constructor() { }

  ngOnInit() {
  }

  handleFileInput(event: Event) {

    const file = (event.target as HTMLInputElement).files[0];

    this.writeValue({
      file
    });
  }

  writeValue(value: ImageFormcontrol.Value) {
    if (this._registerOnTouchedFn) {
      this._registerOnTouchedFn();
    }

    if (this._registerOnChangeFn) {
      // update value and validity
      this._registerOnChangeFn(value);
    }
  }

  registerOnChange(fn) {
    this._registerOnChangeFn = fn;
  }

  registerOnTouched(fn) {
    this._registerOnTouchedFn = fn;
  }

}
<input (change)="handleFileInput($event)"  type="file"  id="file" class="inputfile" accept="image/*" />

2.Добавлены пользовательские правила проверки

изображения FormControl-валидатор

  export function allowedTypes(pattern: string[]): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } | null => {
      const value = control.value as ImageFormcontrol.Value;

      const valid = null;
      const isUndefined = !value || !value.file;
      if (isUndefined) {
        return valid;
      }

      const allowed = new RegExp(`(${pattern.join('|')})`, 'ig').test(value.file.type);
      if (allowed) {
        return valid;
      } else {
        const invalid = { 'allowedTypes': { value: control.value } };
        return invalid;
      }
    };
  }

-

2-1. Регистрация пользовательских правил проверки

app.component (вы можете изменить его на свой компонент, только для демонстрационных целей)

export class AppComponent {

  firstFormGroup: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    const imageFormControl = new FormControl('', ImageFormcontrolValidator.allowedTypes(['jpeg']));

    this.firstFormGroup = this.fb.group({
      image: imageFormControl
    });
  }
}

3. Слушайте изменения событий в ваших реактивных формах

  • Загрузить действительный файл в ваше хранилище

export class AppComponent {

  firstFormGroup: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    const imageFormControl = new FormControl('', ImageFormcontrolValidator.allowedTypes(['jpeg']));

    this.firstFormGroup = this.fb.group({
      image: imageFormControl
    });

    imageFormControl.statusChanges.subscribe((status) => {
      switch (status) {
        case 'VALID':
          // Upload the valid file to your storage
          const value = imageFormControl.value as ImageFormcontrol.Value;
          this.upload(value.file);
          break;
      }
    });
  }

  private upload(file: File) {
    console.log('upload', file);

    /* your custom logic

    const filePath = `${this.rutaImg}/${file.name}`;
        const fileRef = this.storage.ref(filePath);
        const task = this.storage.upload(filePath, file);
        this.uploadPercent = task.percentageChanges();
        task.snapshotChanges().pipe(
            finalize(() => {
              this.downloadURL = fileRef.getDownloadURL();
              this.downloadURL.subscribe( url => {
                if ( url ) {
                  this.urlImg = url;
                  console.log(this.urlImg);
                  this.validateImage = true;
                  console.log(this.validateImage );
                  return {
                    isError: this.validateImage
                };
                }
             });
            })
         )
        .subscribe();

      */
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...