[英]File validation in angular 7
如何在文件上传到服务器之前验证文件大小和文件类型。 以及如何将这种验证与反应式表单或模板驱动的方法一起使用。
默认情况下,响应式或模板驱动的表单不支持文件,因此您需要创建一个自定义ControlValueAccessor来包装 File 变量。 这正是这里所做的。
这是相关部分:
@Component({
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: FileUploadComponent,
multi: true
}
]
})
export class FileUploadComponent implements ControlValueAccessor {
@Input() progress;
onChange: Function;
private file: File | null = null;
@HostListener('change', ['$event.target.files']) emitFiles( event: FileList ) {
const file = event && event.item(0);
this.onChange(file);
this.file = file;
}
constructor( private host: ElementRef<HTMLInputElement> ) {
}
writeValue( value: null ) {
// clear file input
this.host.nativeElement.value = '';
this.file = null;
}
registerOnChange( fn: Function ) {
this.onChange = fn;
}
registerOnTouched( fn: Function ) {
}
}
如果您需要任何验证,那么您可以在此自定义组件中实现它。 只需通过注入获取 NgControl 的引用并相应地调用setErrors 即可。
您可以获取更改事件并检查文件大小和类型
在你的 ts 文件中有这个方法。
readFile(fileEvent: HTMLInputEvent) {
const file: File = fileEvent.target.files[0];
console.log('size', file.size);
console.log('type', file.type);
}
并在您的 html 处理 onchange 事件
<input (change)="readFile($event)" type="file" />
我不确定我的回答是否仍然相关。 但是经过一番挖掘和混乱之后,我想出了这个解决方案(取自我自己的项目)。 请记住,我正在使用多个文件上传。
HTML:
<input type="file" multiple (change)="onFilePicked($event.target.files)" />
组件:假设您正在使用并创建了一个表单构建器
this.formBuilder= this.fb.group({
files: ['', [checkFileType]],
//other fields
})
//custom validation
function checkFileType(control: AbstractControl): { [key: string]: any } | null {
const files: File[] = control.value;
let errors: string[] = [];
if (files.length >= 1 ) {
for (let index = 0; index < files.length; index++) {
//Use a type list here to check for your types for example "image/jpeg"
if (files[index].type === '') {
errors.push(`${files[index].name} has an invalid type of unknown\n`);
}
}
return errors.length >= 1 ? { invalid_type: errors } : null;
}
return null; // no file, can be capture by "Required" validation
}
要捕获 HTML 中的错误:
<div *ngIf="files.errors">
<div class="text-danger" *ngFor="let typeError of files.errors.invalid_type">
<span>- {{ typeError }}.</span>
</div>
</div>
这个解决方案为我做到了。 我希望它也能帮助你。
这个问题几乎可以用 HTML 本身解决。 不需要角度相关的东西。
<form action="/action_page.php">
<input type="file" name="pic" accept="image/*">
<input type="submit">
</form>
可以按如下方式使用 accept 属性:
<input accept="file_extension|audio/*|video/*|image/*|media_type">
接受参数解释如下:
希望这可以帮助 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.