【问题标题】: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.txt 至text.png
【问题讨论】:
标签:
javascript
image
validation
angular
【解决方案1】:
HTML <input> 有一个可以使用的属性。
<input accept=".png, .text" />
【解决方案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')