[英]Submitting multiple files to ASP.NET controller accepting an ICollection<IFormFile>
In my ASP.NET Core backend, I have a controller function that looks like this:在我的 ASP.NET Core 后端,我有一个控制器函数,如下所示:
[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);
}
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.如果“files”是单个文件 - 不是包含一个文件的数组,而是单个 File 对象 -
UploadFile
包含单个文件的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>
.如果“files”是一个文件列表,或者是一个 FileList 或者一个 File 对象数组,
UploadFile
被调用时带有一个空的ICollection<IFormFile>
。
How do I submit a list of files in such a way that they can be parsed as an ICollection<IFormFile>
?如何以可以将文件解析为
ICollection<IFormFile>
的方式提交文件列表?
Reference Uploading multiple files at once - with Fetch参考一次上传多个文件 - 使用 Fetch
uploadDocuments(endPoint, files) {
var postSettings = {
method: 'POST',
credentials: 'include',
mode: 'cors'
};
var data = new FormData();
if(files.length > 0) {
for(var x = 0; x < files.length; x++) {
// the name has to be 'files' so that .NET could properly bind it
data.append('files', files.item(x));
}
}
postSettings.body = data;
return fetch(endPoint + '/documents/upload', postSettings);
}
Reference Uploading small files with model binding参考使用模型绑定上传小文件
When uploading files using model binding and the
IFormFile
interface, the action method can accept either a singleIFormFile
or anIEnumerable<IFormFile>
(orList<IFormFile>
) representing several files.使用模型绑定和
IFormFile
接口上传文件时,操作方法可以接受单个IFormFile
或代表多个文件的IEnumerable<IFormFile>
(或List<IFormFile>
)。 The following example loops through one or more uploaded files, saves them to the local file system, and returns the total number and size of files uploaded.下面的示例循环遍历一个或多个上传的文件,将它们保存到本地文件系统,并返回上传文件的总数和大小。
[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});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.