无法在表单中同时发送文件和对象

Can not send both files and objects within a form

您好,我想知道您如何在表单中同时发送 POCOfiles。 我的问题是双重的:

表格

<form id="createForm" method="post" enctype="multipart/form-data" action="http://localhost:8300/api/create">

<input type="text" bind="@model.Name"/>//some binding here
<input type="text" bind="@model.Id"/> //some binding...

<input type="file"/>
</form>

控制器

[HttpPost]
        [Route("api/create")]
        public async Task<long> CreateAsync([FromBody] MyPoco poco) { //getting error 415 when using the FromBody 
            try {

                MyPoco poc = poco;
                string path = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), 
                    "file.csv"); //copy the input file -> getting 0kb file
                FileStream stream = new FileStream(path, FileMode.Create);
                await this.Request.Form.Files[0].CopyToAsync(stream);
                return 3;
            } catch (Exception) {
                return 0;
            }
        }

P.S 绑定的语法是 blazor 但在这种情况下并不重要。

避免使用[FromBody],它会指示ModelBinder读取整个payload,然后将其序列化为MyPoco.

的实例

为了实现您的目标,您可以声明您的操作方法如下:

[HttpPost("[action]")]
public IActionResult Test(MyPoco myPoco,IFormFile myfile){
     // now you get the myfile file and the myPoco 
}

然后发送具有完整名称的字段:

<form id="createForm" method="post" enctype="multipart/form-data" action="/api/SampleData/Test">

    <input name="MyPoco.Name" type="text" bind="@model.Name" />
    <input name="MyPoco.Id" type="text" bind="@model.Id" />

    <input name="myfile" type="file" />
    <button type="submit">submit this form</button>
</form>

演示截图: