admin管理员组文章数量:1304900
In Angular 2 how to validate if a file is really an image?
isImage(file: File): boolean {
return /^image\//.test(file.type);
}
In the above function after an upload, simply change the .txt
to .png
file extension it returns true
eg: text.txt
to text.png
In Angular 2 how to validate if a file is really an image?
isImage(file: File): boolean {
return /^image\//.test(file.type);
}
In the above function after an upload, simply change the .txt
to .png
file extension it returns true
eg: text.txt
to text.png
4 Answers
Reset to default 3HTML <input>
has an attribute which you can use.
<input accept=".png, .text" />
You can check easily with file type. If example it it's video type will be "video/format" or if it's image it will be "image/format". you can use this.
event.target.files[0].type.includes('image')
The following is not specifically about Angular but it does answer the question of doing client side file type validation in javascript. It should be easy enough to adapt the solution for your needs: How to check file MIME type with javascript before upload?
Here is a custom directive for that. You can use it for other file types too. Just add/remove your required extensions in 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);
}
}
In your ponent,
this.form = new FormGroup({
file: new FormControl("", [FileTypeValidator.validate])
});
本文标签: javascriptAngular 2Validate if a file is really an imageStack Overflow
版权声明:本文标题:javascript - Angular 2 - Validate if a file is really an image - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741793389a2397793.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论