Angular 2 - 验证文件是否真的是图像

时间:2016-09-30 02:45:32

标签: javascript image validation angular

在Angular 2中如何验证文件是否真的是图像?

/usr/lib/x86_64-linux-gnu/libcusolver.so 

在上传后的上述功能中,只需将isImage(file: File): boolean { return /^image\//.test(file.type); } 更改为.txt文件扩展名即可返回.png,例如:truetext.txt

4 个答案:

答案 0 :(得分:1)

以下内容并非专门针对Angular,但它确实回答了在javascript中进行客户端文件类型验证的问题。根据您的需求调整解决方案应该很容易:How to check file MIME type with javascript before upload?

答案 1 :(得分:0)

这是一个自定义指令。您也可以将它用于其他文件类型。只需在RegExp

中添加/删除所需的扩展程序即可
import { FormControl, NG_VALIDATORS, Validator } from '@angular/forms';
import { Directive } from '@angular/core';

@Directive({
  selector: '[FileTypeValidator]',
  providers: [
    {
      provide: NG_VALIDATORS, useExisting: FileTypeValidator, multi: true
    }
  ]
})
export class FileTypeValidator implements Validator {

  static validate(c: FormControl): { [key: string]: any } {
    if (c.value) {
      if (c.value[0]) {
        return FileTypeValidator.checkExtension(c);
      };
    }
  }

  private static checkExtension(c: FormControl) {
    let valToLower = c.value[0].name.toLowerCase();
    let regex = new RegExp("(.*?)\.(jpg|png|jpeg)$"); //add or remove required extensions here
    let regexTest = regex.test(valToLower);
    return !regexTest ? { "notSupportedFileType": true } : null;
  }

  validate(c: FormControl): { [key: string]: any } {
    return FileTypeValidator.validate(c);
  }

}

在您的组件中,

this.form = new FormGroup({
        file: new FormControl("",    [FileTypeValidator.validate])
    });

答案 2 :(得分:0)

HTML <input>具有可以使用的属性。

<input accept=".png, .text" />

答案 3 :(得分:0)

您可以轻松检查文件类型。例如,它的视频类型将是“视频/格式”,或者如果它是图像,它将是“图像/格式”。 你可以用这个。

event.target.files[0].type.includes('image')