【发布时间】: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<HttpPostedFileBase> files为空吗? -
@GuruStron 它不是空的并且有上传的文件
-
我刚刚想通了。我已经更新了我的答案。
标签: c# asp.net-mvc api .net-core asp.net-core-webapi