我创建了带有文本输入的简单反应式表单,当提交表单时,我想传递文件输入中的图像。每次我用谷歌搜索时,我都会得到教程,它们向我展示如何上传文件,但它是在没有其他输入字段的情况下完成的。我知道如何做到这一点,但我不明白如何在一次提交中提交表单和文件输入。
在我的场景中,我是否不应该使用反应式表单,而应该使用简单的表单new FormData()
并将每个输入附加到其中?
如果我能做到这一点,请给我留下简单的例子。
edit: 如何在 Angular2 响应式表单中包含文件上传控件? https://stackoverflow.com/questions/43444440/how-to-include-a-file-upload-control-in-an-angular2-reactive-form这不是答案。回答市场没有随反应形式发布文件,它是单独的发布文件。
也有这个问题,我所做的是构造一个 FormData,使用循环将 formGroup 值添加到表单 Data
import {
Component,
OnInit,
ChangeDetectorRef
} from '@angular/core';
import {
FormGroup,
FormBuilder,
Validators
} from '@angular/forms';
export class TodoFormComponent {
todoForm: FormGroup = this.fb.group({
todo: ['', Validators.required],
image: ['', Validators.required], //making the image required here
done: [false]
})
constructor(
private fb: FormBuilder,
private cd: ChangeDetectorRef
) {}
/**
*@param event {EventObject} - the javascript change event
*@param field {String} - the form field control name
*/
onFileChange(event, field) {
if (event.target.files && event.target.files.length) {
const [file] = event.target.files;
// just checking if it is an image, ignore if you want
if (!file.type.startsWith('image')) {
this.todoForm.get(field).setErrors({
required: true
});
this.cd.markForCheck();
} else {
// unlike most tutorials, i am using the actual Blob/file object instead of the data-url
this.todoForm.patchValue({
[field]: file
});
// need to run CD since file load runs outside of zone
this.cd.markForCheck();
}
}
onSubmit() {
const formData = new FormData();
Object.entries(this.todoForm.value).forEach(
([key, value]: any[]) => {
formData.set(key, value);
}
//submit the form using formData
// if you are using nodejs use something like multer
)
}
}
<form [formGroup]="todoForm" (ngSubmit)="onSubmit()">
<input type="file" formControlName="image" (onchange)="onFileChange($event, 'image')"/>
<textarea formControlName="todo"></textarea>
<button type="submit">Submit</button>
</form>
在服务器端,您可以像处理表单数据请求一样处理请求
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)