Angular 2:文件扩展名的自定义验证

时间:2017-03-15 04:00:32

标签: angular angular2-forms angular2-directives

我是棱角分明的新人。我想创建一个自定义验证来检查文件大小和扩展名。我使用FormBuilder进行验证,使用FileReader API获取输入元素字段数据的文件名和大小。

问题:我们能够在更改事件上触发自定义验证,但无法获取输入类型字段的值。

请建议我们如何为角度2中的文件扩展名和大小实现自定义验证。

HTML:

<input type="file" [formControl] = "formName.controls['thumbnailImg']" (change)="changeThumbFile($event)">

组件:

//custom validation
function validateExt(c: FormControl) {
    let extension = ['png', 'jpeg', 'gif'];
    return extension.indexOf(c.value)? null : { validateExt: { valid: false } }
}

this.form = this.formBuilder.group({
  'thumbnailImg': ['', validateExt],
});
changeThumbFile($event){
    var file: File = $event.target.files[0];
    var fReader: FileReader = new FileReader();

    var imgName = file.name;
    this.thumbnailName = imgName;

    this.formGp.controls['thumbnailImg'].updateValueAndValidity();
}

1 个答案:

答案 0 :(得分:6)

我有一个解决方案,也许不是一个完美的解决方案,但它有效(同样的文件大小),这里是:

首先在html文件中我得到了文件上传的表单,每次我上传文件时都会调用一个名为fileEvent()的特定函数,该布局文件包含:

   <form [formGroup]="photoForm" (submit)="savePhoto()">
          <table>
            <tr>
              <td>Photo</td>
              <td>
                <div class="file-edit">
                  <input type="file" (change)="fileEvent($event)" formControlName="newPhoto" class="form-control" required #newPhoto>
                </div>
              </td>
              <td><p class="warning">{{fileExtensionMessage}}</p></td>
            </tr>
            <br/>
            <tr>
              <td></td>
              <td><button type="submit" [disabled]='fileExtensionError' class="submit-btn">Save</button></td>
            </tr>
          </table>
        </form>

请注意,如果fileExtensionError变量为true,则禁用提交按钮。

检查验证的函数fileEvent()也给我文件名,文件扩展名和文件内容如下:

 fileEvent(event) : any {
    //*-- this function gets content of uploaded file and validation --
     */
    var file = event.target.files[0];
    this.photoName = file.name;

    var allowedExtensions = 
       ["jpg","jpeg","png","JPG","JPEG","JFIF","BMP","SVG"];
    this.fileExtension = this.photoName.split('.').pop();

    if(this.isInArray(allowedExtensions, this.fileExtension)) {
        this.fileExtensionError = false;
        this.fileExtensionMessage = ""
    } else {
        this.fileExtensionMessage = "Only photos allowed!!"
        this.fileExtensionError = true;
    }

    if (file) {
        var reader = new FileReader();
        reader.onloadend = (e: any) => {
            var contents = e.target.result;
            this.photoContent = contents;
        }
        reader.readAsDataURL(file);
    } else {
        alert("Failed to load file");
    }
}

/*- checks if word exists in array -*/
 isInArray(array, word) {
    return array.indexOf(word.toLowerCase()) > -1;
}

当然我在我的班级中声明了这些变量:

photoName: any;
photoContent : any;
fileExtension: any;
fileExtensionError: boolean = false;
fileExtensionMessage: any;
photoForm : FormGroup;

希望它有助于某人:D