【问题标题】:Angular 2 - Validate if a file is really an imageAngular 2 - 验证文件是否真的是图像
【发布时间】:2016-09-30 02:45:32
【问题描述】:

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

isImage(file: File): boolean {
    return /^image\//.test(file.type);
}

在上传后的上述函数中,只需将.txt 更改为.png 文件扩展名即可返回true 例如:text.txttext.png

【问题讨论】:

    标签: javascript image validation angular


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        这是一个自定义指令。您也可以将其用于其他文件类型。只需在 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])
            });
        

        【讨论】:

          【解决方案4】:

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

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

          【讨论】:

            猜你喜欢
            • 2010-12-13
            • 2017-03-06
            • 2015-12-02
            • 2018-05-09
            • 2011-09-17
            • 2013-03-10
            • 1970-01-01
            • 1970-01-01
            • 2011-08-12
            相关资源
            最近更新 更多