首页 > 解决方案 > 无法在表单中同时发送文件和对象

问题描述

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

形式

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

PS绑定的语法是,blazor但在这种情况下并不重要。

标签: formsasp.net-coremultipart

解决方案


避免使用[FromBody],它将指示 ModelBinder 读取整个有效负载,然后将其序列化为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>

演示截图:

在此处输入图像描述


推荐阅读