[英]angular send data from formData and formGroup simultaneously
是否可以发送带有反应形式(模型驱动)的文件? 文件来自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)" />
创建FormControl
和FormGroup
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);
}
将数据发送到节点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();
};
}
}
在您的推送数据中,更改
this.userData('file').setValue(this.readyFile)
到
this.userData.get('file').setValue(this.readyFile)
你可以从这个文件上传中获得更多参考
很久没有问你的问题了,但我认为这可以帮助你(或任何提出这个问题的人)
public toFormData<T>( formValue: T ) { const formData = new FormData(); for ( const key of Object.keys(formValue) ) { const value = formValue[key]; formData.append(key, value); } return formData; } onSubmit() { if (this.userData.valid) { let filelist: FileList = this.files; const formData = this.toFormData(this.userData) for (let i = 0; i < filelist.length; i++) { this.readyFile = filelist[i]; formData.append('file[]', this.readyFile[0]); } this.apiService.updateUserData(formData) } }
首先,您将表单作为 FormData,然后将数组中的每个文件添加到该 FormData(不要忘记“[]”来上传多个文件)
您可以为要发送的每个 FormControl 执行一个新的 formData.append()。
formData.append('name', this.name.value)
formData.append('surname', this.surname.value)
formData.append('email', this.email.value)
formData.append('file', this.file.value)
我对这个解决方案并不满意,但这是我找到的唯一解决方案。 希望它可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.