【问题标题】:.NET Core API List<IFormFile> files not received from .NET MVC MultipartFormDataContent POST.NET Core API List<IFormFile> 文件未从 .NET MVC MultipartFormDataContent POST 接收
【发布时间】:2020-09-19 20:47:52
【问题描述】:

我在下面有一个 .NET Core API POST 方法:

    public IActionResult UploadFiles([FromForm(Name = "files")] List<IFormFile> files, [FromForm(Name = "providerName")] string providerName) 
    {
        try
        {
            return WriteToXlsx(files,providerName); //documents
        }
        catch (Exception ex)
        {

            return BadRequest($"Error: {ex.Message}");
        }
    }

从 Postman 发帖时工作正常,收到文件。 但是,当尝试如下所示从 ASP.NET MVC 发布时,似乎没有收到文件。没有错误消息,但列表文件中的文件计数为零。正在接收字符串“providerName”。

    [HttpPost]
    public async Task<ActionResult> ContentTransformation(IEnumerable<HttpPostedFileBase> files, string providerName)
    {
      
        try
        {
            HttpClientHandler clientHandler = new HttpClientHandler();
            var httpClient = new HttpClient(clientHandler);
            var multipartFormDataContent = new MultipartFormDataContent();

            foreach (HttpPostedFileBase file in files)
            {
                byte[] fileData;
                using (var reader = new BinaryReader(file.InputStream))
                {
                    fileData = reader.ReadBytes(file.ContentLength);
                }
                var fileContent = new ByteArrayContent(fileData);
                multipartFormDataContent.Add(fileContent, "files");
            }

            StringContent sProviderName = new StringContent(providerName);
            multipartFormDataContent.Add(sProviderName, "\"providerName\"");

            var response = await httpClient.PostAsync(ConfigurationManager.AppSettings["ContentTransformationAPI"], multipartFormDataContent);

            FileContentResult metadataContent = new FileContentResult(response.Content.ReadAsByteArrayAsync().Result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            return File(
                fileContents: metadataContent.FileContents,
                contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                fileDownloadName: "metadata.xlsx"
                );
        }
        catch (Exception ex)
        {

            ViewBag.Message = "File upload failed!! " + ex.Message;
            ModelState.Clear();
            return View();
        }
    }

【问题讨论】:

  • 这将是您发布的视图的问题。表单输入元素必须调用files,以匹配控制器操作中的files 参数,否则模型绑定器将不会拾取它。
  • 嗨@JohnH 它被称为“文件”:
  • @user2248185 在ContentTransformation 中是IEnumerable&lt;HttpPostedFileBase&gt; files 为空吗?
  • @GuruStron 它不是空的并且有上传的文件
  • 我刚刚想通了。我已经更新了我的答案。

标签: c# asp.net-mvc api .net-core asp.net-core-webapi


【解决方案1】:

编辑

我发现了问题。您正在丢弃上传的FileName,因此当您将数据从 MVC 控制器发布到 API 控制器时,它不会正确绑定。您需要更改的只是:

multipartFormDataContent.Add(fileContent, "files");

multipartFormDataContent.Add(fileContent, "files", file.FileName);

然后文件将被正确绑定。

旧答案

您的代码(控制器 + 表单元素)对我有用,这让我认为您的表单设置不正确。最简单的应该是这样的:

@using (Html.BeginForm(
    "ContentTransformation", 
    "YourControllerName", // Make sure you change this.
    FormMethod.Post, 
    new { enctype = "multipart/form-data" }))
{
    <input type="file" name="files" multiple="multiple" />
    <input type="submit" />
}

我认为您可能缺少的部分是new { enctype = "multipart/form-data" }multipart/form-data enctype 允许输入元素上传文件数据,因此没有它您的上传器将无法工作。

【讨论】:

  • OP 尝试使用HttpClient 发送文件。
  • @GuruStron 请检查 cmets。 OP 正在使用带有输入元素的表单。
  • 我已经删除了它。尽管从 OP 的回答来看,问题出在ContentTransformation 上仍不清楚。
  • @GuruStron 我明白你在说什么 - 问题的第二段是模棱两可的,所以这可能意味着问题是表单的发布,或者它可能是来自 MVC 的部分发布 - > API。
  • 感谢@JohnH,添加 file.FileName 解决了我的问题!
猜你喜欢
  • 2021-12-18
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多