确保 FormData 对象包含所需的键值对
设置 Content-Type 标头为 'multipart/form-data'
在 .Net Core webAPI 中使用 FromForm 属性将 FormData 数据绑定到模型。
示例代码:
Angular 控制器代码
submitForm() {
const formData = new FormData();
formData.append('name', this.name);
formData.append('email', this.email);
formData.append('avatar', this.avatarFile, this.avatarFile.name);
this.http.post('/api/users', formData).subscribe(res => {
console.log(res);
});
}
.Net Core webAPI 控制器代码
[HttpPost]
public async Task AddUser([FromForm] UserDto userDto) {
// userDto now contains the FormData submitted from the Angular app
// handle saved to DB, etc.
return Ok();
}