gpt4 book ai didi

c# - .NET Core API List 文件未从 .NET MVC MultipartFormDataContent POST 接收

转载 作者:行者123 更新时间:2023-12-04 08:53:32 28 4
gpt4 key购买 nike

我在下面有一个 .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();
}
}

最佳答案

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

multipartFormDataContent.Add(fileContent, "files");
multipartFormDataContent.Add(fileContent, "files", file.FileName);
然后文件将被正确绑定(bind)。
旧答案
您的代码( Controller + 表单元素)对我有用,这让我认为您的表单设置不正确。在最简单的情况下,它应该如下所示:
@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 允许输入元素上传文件数据,因此没有它您的上传器将无法工作。

关于c# - .NET Core API List<IFormFile> 文件未从 .NET MVC MultipartFormDataContent POST 接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63973265/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com