将多个文件提交给ASP.NET控制器,接受ICollection <iformfile>

时间:2017-04-17 17:08:20

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

在我的ASP.NET Core后端,我有一个如下所示的控制器功能:

[HttpPost]
[Route("documents/upload")]
public async Task<IActionResult> UploadFile(ICollection<IFormFile> files)
{
   ...
}

在我的前端,我将这个函数称为:

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);
}

如果&#34;文件&#34;是单个文件 - 不是包含一个文件的数组,而是使用包含单个文件的UploadFile调用单个File对象ICollection<IFormFile>

如果&#34;文件&#34;是一个文件列表,无论是FileList还是File对象数组,UploadFile都是空的ICollection<IFormFile>

如何以可以将其解析为ICollection<IFormFile>的方式提交文件列表?

1 个答案:

答案 0 :(得分:7)

参考Uploading multiple files at once - with Fetch

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);
}

参考Uploading small files with model binding

  

使用模型绑定和IFormFile上传文件时   接口,action方法可以接受单个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});
}