将多个文件提交到接受ICollection< IFormFile>的ASP.NET控制器. [英] Submitting multiple files to ASP.NET controller accepting an ICollection<IFormFile>
问题描述
在我的ASP.NET Core后端中,我有一个类似于以下的控制器功能:
In my ASP.NET Core backend, I have a controller function that looks like this:
[HttpPost]
[Route("documents/upload")]
public async Task<IActionResult> UploadFile(ICollection<IFormFile> files)
{
...
}
在我的前端,我这样调用函数:
In my front-end, I call the function like this:
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);
}
如果文件"是单个文件-不是包含一个文件的数组,而是单个File对象-UploadFile
会被包含单个文件的ICollection<IFormFile>
调用.
If "files" is a single file - not an array with one file, but a single File object - UploadFile
is called with an ICollection<IFormFile>
containing the single file.
如果文件"是文件列表,即FileList或File对象数组,则使用空的ICollection<IFormFile>
调用UploadFile
.
If "files" is a list of files, either a FileList or an array of File objects, UploadFile
is called with an empty ICollection<IFormFile>
.
如何提交文件列表以使它们可以被解析为ICollection<IFormFile>
?
How do I submit a list of files in such a way that they can be parsed as an 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);
}