我有一个用ASP.NET Core Web API 2.1编写的文档服务API。该API当前接受包含1个文件信息的ViewModel,然后将该文件和信息保存到服务器。我想添加添加多个文件的功能,但是当作为集合的一部分上载时,无法绑定IFormFile
文件。
/// The ViewModel being uploaded.
public class FileUploadDto
{
public Guid Id { get; set; }
public string Description { get; set; }
public string Name { get; set; }
public IFormFile File { get; set; }
}
/// Works perfect. All properties are bound to the fileUploadRequest object.
[HttpPost]
public async Task<IActionResult> Add(FileUploadDto fileUploadRequest)
{
/// Process
return Ok();
}
/// All properties are bound to the objects in the collection, except for the File property.
[HttpPost]
public async Task<IActionResult> AddRange([FromForm] IEnumerable<FileUploadDto> fileUploadRequests)
{
foreach (FileUploadDto fileUploadRequest in fileUploadRequests)
{
//fileUploadRequest.File is null
}
return Ok();
}
我正在使用邮递员对此进行测试,并使用表单数据将正文中的内容上传为:
[0] [说明]:测试(类型:文本)
[0] [名称]:测试(类型:文本)
[0] [文件]:sample.txt(类型:文件)
multipart/form-data
在内容类型标题中设置。
更新:
通过执行以下操作,我找到了一种解决方法,但是显然这不是最好的方法。我认识到问题在于文件没有绑定到我的ViewModels,而是存储在Request.Form.Files
集合中。不过,我不确定该如何解决。
[HttpPost]
public async Task<IActionResult> AddRange([FromForm] IEnumerable<FileUploadDto> fileUploadRequests)
{
var index = 0;
foreach (FileUploadDto fileUploadRequest in fileUploadRequests)
{
//fileUploadRequest.File is null
fileUploadRequest.File = Request.Form.Files[index];
index += 1;
}
return Ok();
}
答案 0 :(得分:0)
我最终传递了一个附加属性,以指定要在请求表中使用的文件索引。
/// The ViewModel being uploaded.
public class FileUploadDto
{
public Guid Id { get; set; }
public string Description { get; set; }
public string Name { get; set; }
public int? FileIndex { get; set; }
public IFormFile File { get; set; }
}
/// Works perfect. All properties are bound to the fileUploadRequest object.
[HttpPost]
public async Task<IActionResult> Add(FileUploadDto fileUploadRequest)
{
/// Process
return Ok();
}
/// All properties are bound to the objects in the collection, except for the File property.
[HttpPost]
public async Task<IActionResult> AddRange([FromForm] IEnumerable<FileUploadDto> fileUploadRequests)
{
foreach (FileUploadDto fileUploadRequest in fileUploadRequests)
{
fileUploadRequest.File = Request.Form.Files[fileUploadRequest.FileIndex ?? -1];
}
return Ok();
}