文章约定
angular版本:8.2.0
组件库:NG-ZOORO
ts代码
// 申明表单名字
addForm: FormGroup;
// 是否上传;
uploading = false;
// 上传文件列表
fileList: UploadFile[] = [];
constructor(
private http: HttpClient,
private fb: FormBuilder,
) { }
ngOnInit() {
// 初始化表单
this.initForm();
}
initForm() {
this.addForm = this.fb.group({
name: [null],
filePath: [null],
});
}
// 这个方法很重要,表示点击上传按钮不自动上传,提交表单的时候才上传文件
beforeUploadFile = (file: UploadFile): boolean => {
this.fileList = this.fileList.concat(file);
return false;
}
// 这是表单的提交方法,注意:务必使用 => 定义处理方法。
submit = () => {
if (this.addForm.valid) {
this.uploading = true;
const formData = new FormData();
const formValue = this.addForm.value;
for (const key in formValue) {
formData.append(key, formValue[key] ? formValue[key] : '');
}
// 这里将表单中上传的名字删除,放入文件
formData.delete('filePath');
this.fileList.forEach((file: any) => {
formData.append('filePath', file);
});
// 这里向后台发送ajax
this.http.post(‘这是后端地址’, formData).subscribe(() => {
// 这里处理返回逻辑
this.uploading = false;
this.fileList = [];
});
}
}
=======================================================================
html代码:
<div>
<!--注意一下这个表单提交方法,如果自定义了submit()点击事件,(ngSubmit)="submit"就不能加();
加了括号表示方法,如果没有自定义submit方法,这里就可以加上();
我在button自定义了一个事件所以这里就不加()了
-->
<form nz-form [formGroup]="addForm" (ngSubmit)="submit">
<nz-form-item>
<nz-form-label [nzSm]="6" [nzXs]="24" nzRequired nzFor="name">文件名</nz-form-label>
<nz-form-control [nzSm]="14" [nzXs]="24" [nzErrorTip]="errTip">
<input nz-input formControlName="name" id="name"/>
</nz-form-control>
</nz-form-item>
<nz-form-item nz-row>
<nz-form-label [nzSm]="6" [nzXs]="24" nzFor="filePath">上传文件</nz-form-label>
<nz-form-control [nzSm]="14" [nzXs]="24">
<nz-upload formControlName="filePath" ngDefaultControl
[(nzFileList)]="fileList"
[nzShowButton]="fileList.length < 1"
[nzBeforeUpload]="beforeUploadFile"
[nzName]="'filePath'"
>
<button nz-button ><i nz-icon nzType="upload"></i>请点击按钮上传文件</button>
</nz-upload>
</nz-form-control>
</nz-form-item>
<button nz-button nzType="primary" (click)="submit()" [nzLoading]="uploading">保存</button>
</form>
<ng-template #errTip let-control>
<ng-container *ngIf="control.hasError('required')">必填</ng-container>
<ng-container *ngIf="control.hasError('maxlength')">过长</ng-container>
</ng-template>
</div>
==========================结束
总结:
1、ng-zooro组件的上传控件,在点击之后会自动上传,所以要在上传之前定义一个不让他自动上传的状态,然后在点击提交表单的时候上传;
2、在表单内有文件的时候要单独对文件进行处理,否则就是提交上传文件的名字;
具体参考官方文档:https://ng.ant.design/version/8.5.x/components/upload/zh