【发布时间】:2021-05-23 09:24:35
【问题描述】:
我对文件上传的表单输入验证有问题。当文件上传为空时,如何验证 formControle 输入。如何在 selectFile 中设置值,以便当文件输入为空时,将显示我从服务器响应中获得的验证消息。
我从服务器获取其他字段名称和姓氏的响应消息,这是因为我在 Html 中使用了 formControlName,这工作正常。但是我不能在文件上传的输入字段中使用 formControlName 属性。
如何在不使用 formControlname 的情况下获取文件输入字段的验证响应消息?
html代码
<input type="text" placeholder="Name" formControlName="name" class="form-control" matInput />
<span *ngIf="inputErrorMessage?.name">{{inputErrorMessage.name}}</span>
<input accept="*" type="file" (change)="selectFile($event)">
<span *ngIf="inputErrorMessage?.file1">{{inputErrorMessage.file1}}</span>
component.ts 代码
constructor(private uploadService: FileuploadService) {
this.form = new FormGroup({
name: new FormControl('' , Validators.required),
familyName: new FormControl('' , Validators.required),
file1: new FormControl('' , Validators.required),
file2: new FormControl('' , Validators.required),
});
}
selectFile(event): void {
const file = event.target.files[0];
this.form.patchValue({
file1: file,
file2: file
});
}
onSubmit(): void {
const formData: any = new FormData();
formData.append('name', this.form.get('name').value);
formData.append('familyName', this.form.get('familyName').value);
formData.append('file1', this.form.get('file1').value);
formData.append('file2', this.form.get('file2').value);
this.uploadService.uploadFiles(formData).subscribe( data => {
this.successMessage = data.message;
},
err => {
console.log(err);
this.inputErrorMessage = err.error.error;
console.log('Errors', this.inputErrorMessage);
this.errorMessage = err.error.message;
console.log('Message', this.errorMessage);
}
);
}
uploadService.ts
uploadFiles(formData): Observable<any> {
return this.http.post(this.urlResume, formData);
}
我已经尝试过一些类似的例子,但没有成功:
Using reactive form validation with <input type="file"> for an Angular app
【问题讨论】:
标签: angular typescript spring-boot multipartform-data