[英]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.