Sim*_*sen 6 c# asp.net-core-mvc fetch-api asp.net-core iformfile
在我的ASP.NET Core后端,我有一个控制器函数,如下所示:
[HttpPost]
[Route("documents/upload")]
public async Task<IActionResult> UploadFile(ICollection<IFormFile> files)
{
...
}
Run Code Online (Sandbox Code Playgroud)
在我的前端,我调用这样的函数:
var postSettings = {
method: 'POST',
credentials: 'include',
mode: 'cors'
}
uploadDocuments( files ) {
var data = new FormData();
data.append('files', files);
postSettings.body = data;
return fetch(endPoint + '/documents/upload', postSettings);
}
Run Code Online (Sandbox Code Playgroud)
如果"files"是单个文件 - 不是具有一个文件的数组,而是单个File对象 - UploadFile则使用ICollection<IFormFile>包含单个文件的文件进行调用.
如果"files"是文件列表,UploadFile则调用FileList或File对象数组为空ICollection<IFormFile>.
如何以可以解析为ICollection<IFormFile>?的方式提交文件列表?
uploadDocuments(endPoint, files) {
var postSettings = {
method: 'POST',
credentials: 'include',
mode: 'cors'
};
var data = new FormData();
if(files.length > 1) {
for(var x = 0; x < files.length; x++) {
data.append('file' + x, files.item(x));
}
} else {
data.append('files', files);
}
postSettings.body = data;
return fetch(endPoint + '/documents/upload', postSettings);
}
Run Code Online (Sandbox Code Playgroud)
使用模型绑定和
IFormFile接口上载文件时,操作方法可以接受单个IFormFile或IEnumerable<IFormFile>(或List<IFormFile>)表示多个文件.以下示例循环遍历一个或多个上载的文件,将它们保存到本地文件系统,并返回上载的文件的总数和大小.
[HttpPost]
[Route("documents/upload")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
}
// process uploaded files
// Don't rely on or trust the FileName property without validation.
return Ok(new { count = files.Count, size, filePath});
}
Run Code Online (Sandbox Code Playgroud)