代码之家  ›  专栏  ›  技术社区  ›  Bercovici Adrian

不能同时发送表单中的文件和对象

  •  1
  • Bercovici Adrian  · 技术社区  · 6 年前

    你好,我想知道你怎么能把 POCO files 在一种形式内。 我的问题是双重的:

    • 1.到目前为止,当我接近 Request.Form.Files[0] 把它复制到一个文件里 0kb 文件。
    • 如果我想得到 MyPoco 当我使用 [FromBody] 作为我方法的参数,我得到 415 不支持的类型。

    形式

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

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   itminus    6 年前

    避免使用 [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>
    

    演示截图:

    enter image description here