[英]How to pass other parameter with file to ASP.NET Core controller from Angular?
I have a problem, I need to pass model as first a parameter, and as the second parameter, I need to pass a file我有一个问题,我需要传递 model 作为第一个参数,作为第二个参数,我需要传递一个文件
Adding a file to a form:将文件添加到表单:
const formDate = new FormData();
formDate.append("File", this.file);
Sending data from angular:从 angular 发送数据:
this.dataService.createRestaurant(this.restaurant, formDate)
.subscribe((data: Restaurant) => this.loadProducts(data))
Data sending service:数据发送服务:
createRestaurant(model: Restaurant, form: FormData){
const headers = new HttpHeaders().append("Content-Disposition", "multipart/form-data")
return this.http.post(this.url, {model, form}, {headers: headers});
}
Controller in Asp.net core: Asp.net 内核中的 Controller:
public IActionResult Post(Restaurant restaurant, IFormFile File)
{
code...
}
I tried to solve this problem for two days, the model is transferred normally, but the file is always null我试了两天解决这个问题,model传输正常,但是文件总是null
Try to change your action to this:尝试将您的操作更改为:
public IActionResult Post(RestaurantViewModel viewModel)
{
code...
}
by creating a ViewModel通过创建一个 ViewModel
public RestaurantViewModel
{
public Restaurant restaurant {get; set;}
public IFormFile File {get; set;}
}
This is how you shape the data into a form这就是您将数据塑造成表格的方式
const formDate = new FormData();
formDate.append("restaurant", JSON.stringify(this.restaurant));
formDate.append("file", this.file[0], this.file[0].name);
"this.restaurant" is exactly the same data model as in Asp.Net Core “this.restaurant”与 Asp.Net Core 中的数据 model 完全相同
Accept json data as in this question: ASP.NET Core and formdata binding with file and json property在这个问题中接受 json 数据: ASP.NET Core and formdata binding with file and json property
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.