如何在Angular和MDBootstrap拖放文件上传中上传和发布单个动态表单字段的图像

时间:2019-11-21 14:18:39

标签: angular mdbootstrap

如何使用有角度的HttpClient发布动态表单字段和上传的图像。

dynamic form generation with file upload image

属性     文件:文件|空值;     dynamicForm:FormGroup;

角形生成器

 ngOnInit() {
this.dynamicForm = this.formBuilder.group({
  numberOfProductsEnterings: ['', Validators.required],
  productsForm: new FormArray([])
});
}

用于访问表单值的获取器

get f() { return this.dynamicForm.controls; }
get p() { return this.f.productsForm as FormArray; }

//动态添加或删除表单字段

onChangeEnterings(e: { target: { value: number; }; }) {
const numberOfProductsEnterings = e.target.value || 0;

if (this.p.length < numberOfProductsEnterings) {
  for (let i = this.p.length; i < numberOfProductsEnterings; i++) {
    this.p.push(this.formBuilder.group({
      name: ['', Validators.required],
      brand: ['', Validators.required],
      color: ['', Validators.required]
    }));
  }

} else {

  for (let i = this.p.length; i >= numberOfProductsEnterings; i--) {
    this.p.removeAt(i);
  }
}
}

标题

httpOptions = {
headers: new HttpHeaders({
  'Content-Type': 'application/json'
})
};

图像/文件上传方法

onFileAdd(file: any) {
this.file = file;
// console.log(`this is file:: ${JSON.stringify(file, null, 4)}`);
}



onFileRemove() {
this.file = null;
}

添加产品方法

addProducts(newPro: ProductInterface[]) {

return this.http.post<ProductInterface[]>(`http://localhost:8080/addProducts`,

  JSON.stringify(newPro), this.httpOptions ); }

在表单提交中

onAddProductsForm() {
this.submitted = true;
// this.loading = true;

// stop here if form is invalid
if (this.dynamicForm.invalid) {
  return;
}

const obj = Object.assign(this.dynamicForm.value, { file: this.file });

// display form values on success
console.log('SUCCESS!! :-)\n\n' + obj, null, 4));

this.addProducts(this.p.value)
  .pipe(first())
  .subscribe(
    (data: any) => {
      // console.log(`log storing: ${data.success}`);
      this.success = data.success || 'Successfully added';
    },
    error => {
      this.error = error;
    });
 }

这是html表单

<form [formGroup]="dynamicForm" (ngSubmit)="onAddProductsForm()">

<select class="px-3 form-control rounded" formControlName="numberOfProductsEnterings"
                (change)="onChangeEnterings($event)"
                [ngClass]="{ 'is-invalid': submitted && !!f.numberOfProductsEnterings.errors }">
                <option *ngFor="let i of [1,2,3,4,5,6,7,8,9,10]" [disabled]="loading">{{i}}</option>
            </select>

<input type="text" id="name" class="form-control" formControlName="name">

<input type="text" id="brand" class="form-control" formControlName="brand">

<input type="text" id="color" class="form-control" formControlName="color">

<mdb-file-upload #uploader (fileRemoved)="onFileRemove()" (fileAdded)="onFileAdd($event)"></mdb-file-upload>

<button type="submit">Add Products</button>

</form>

0 个答案:

没有答案