ASP.NET Core Web API IFormFile 为空,发送 FormData 请求时

Pri*_*era 5 multipartform-data fetch-api asp.net-core-webapi iformfile

我正在使用 Aurelia Fetch Client 向 Web API 端点发送文件上传请求。但是 IFormFile 是空的所有磁贴。我的代码如下。

客户端

const formData = new FormData();
formData.append("files", account.statement);

const response = await this.http.fetch(url, { method: "POST", body: formData 
});
Run Code Online (Sandbox Code Playgroud)

Web API 端点

[HttpPost]
public IActionResult Save    ()
{
    var files = Request.Form.Files;
}
Run Code Online (Sandbox Code Playgroud)

文件始终为空。我已经关注了这篇文章,并按照上面提到的做了。但仍然无法弄清楚什么是错的。

Pri*_*era 3

我想出了一种方法,使用 DTO 并将上传的文件指定为 FormData 中的 File 对象。这是因为我需要与 File 对象一起发送其他字段值。

服务器

创建具有所需属性的 DTO 对象。

public class SaveAccountRequest
{
    public string AccountName { get; set; }
    public IFormFile Statement { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

将 DTO 添加为控制器端点中接受的参数。

[HttpPost]
public IActionResult SaveAccount([FromForm] SaveAccountRequest saveAccountRequest)
{
//you should be able to access the Statement property as an IFormFile in the saveAccountRequest.
}
Run Code Online (Sandbox Code Playgroud)

客户

将所有属性附加到 FormData 对象,并确保根据服务器端 DTO 中使用的名称命名它们。

const formData = new FormData();
formData.append("accountName", accountName);
formData.append("statement", file);
Run Code Online (Sandbox Code Playgroud)

将数据发布到 SaveAccount 端点。我正在使用 fetch API 来发布数据,但简单的发布也应该可以。发送文件请求时,请确保将内容类型设置为多部分表单数据。

this.http.fetch(<api endpoint url>, { method: "POST", body: formData, content-type: 'multipart/form-data' });
Run Code Online (Sandbox Code Playgroud)