gpt4 book ai didi

node.js - Angular 同时从 formData 和 formGroup 发送数据

转载 作者:太空宇宙 更新时间:2023-11-04 01:41:15 25 4
gpt4 key购买 nike

是否可以使用响应式(Reactive)表单(模型驱动)发送文件?文件来自formData,另一个数据来自FormGroup,如何组合它们并发送到nodejs?

从以下位置获取文件:

<input formControlName="name" class="form-control" type="text">
<input formControlName="surname" class="form-control" type="text">
<input formControlName="email" class="form-control" type="mail">
<input type="file"(change)="addPhoto($event)" />

创建FormControlFormGroup

createFormControls() {
this.name = new FormControl("", Validators.required);
this.surname = new FormControl("", Validators.required);
this.email = new FormControl();
this.file = new FormControl("");
}

createForm() {
this.userData = new FormGroup({
name: this.name,
surname: this.surname,
email: this.email,
file: this.file
});
}

推送数据

addPhoto(event) {
let target = event.target || event.srcElement;
this.files.push(target.files);
}

发送数据到node js

onSubmit() {
if (this.userData.valid) {
let filelist: FileList = this.files;
const formData = new FormData();
for (let i = 0; i < filelist.length; i++) {
this.readyFile = filelist[i];
formData.append('file', this.readyFile[0]);
}
// Here I have a main problem - there are "formData" and
// "this.userData.value" how send it to together(concat) ?

this.apiService.updateUserData(--?--)
}
}

最佳答案

在addPhoto中,替换为以下代码。

addPhoto(event) {
let reader = new FileReader();

if(event.target.files && event.target.files.length) {
const [file] = event.target.files;
reader.readAsDataURL(file);

reader.onload = () => {
this.formGroup.patchValue({
file: reader.result
});

// need to run CD since file load runs outside of zone
this.cd.markForCheck();
};
}
}

关于node.js - Angular 同时从 formData 和 formGroup 发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52830638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com