【问题标题】:How to pass other parameter with file to ASP.NET Core controller from Angular?如何将文件中的其他参数从 Angular 传递给 ASP.NET Core 控制器?
【发布时间】:2021-08-19 01:15:57
【问题描述】:

我有一个问题,我需要将模型作为第一个参数传递,作为第二个参数,我需要传递一个文件

将文件添加到表单:

const formDate = new FormData();
formDate.append("File", this.file);

从角度发送数据:

this.dataService.createRestaurant(this.restaurant, formDate)
    .subscribe((data: Restaurant) => this.loadProducts(data))

数据发送服务:

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});
  }

Asp.net 核心中的控制器:

public IActionResult Post(Restaurant restaurant, IFormFile File)
    {
       code...
    }

我试了两天解决这个问题,模型传输正常,但是文件总是为空

【问题讨论】:

    标签: c# angular asp.net-core asp.net-core-webapi


    【解决方案1】:

    尝试将您的操作更改为:

    public IActionResult Post(RestaurantViewModel viewModel)
        {
           code...
        }
    

    通过创建 ViewModel

    public RestaurantViewModel
    {
    public Restaurant restaurant {get; set;}
    public IFormFile File {get; set;}
    }
    

    【讨论】:

    • 我已经尝试过了,我尝试了很多东西,但没有成功。
    • 您是否尝试添加 [FromBody] 例如?
    • 是的,我试过 [FromBody] 和 [FromForm]
    • 我不知道餐厅是什么,但您是否也尝试将其附加到表单中?
    • 我不确定你是否需要明确添加 const headers = new HttpHeaders().append("Content-Disposition", "multipart/form-data")
    【解决方案2】:

    这就是您将数据塑造成表格的方式

    const formDate = new FormData();
    formDate.append("restaurant", JSON.stringify(this.restaurant));
    formDate.append("file", this.file[0], this.file[0].name);
    

    “this.restaurant”与 Asp.Net Core 中的数据模型完全相同

    在这个问题中接受 json 数据: ASP.NET Core and formdata binding with file and json property

    【讨论】:

      猜你喜欢
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      • 2010-09-14
      • 2019-04-20
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多