向接受 ICollection<IFormFile> 的 ASP.NET 控制器提交多个文件

Submitting multiple files to ASP.NET controller accepting an ICollectionlt;IFormFilegt;(向接受 ICollectionlt;IFormFilegt; 的 ASP.NET 控制器提交多个文件)
本文介绍了向接受 ICollection<IFormFile> 的 ASP.NET 控制器提交多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

[HttpPost][路线(文件/上传")]公共异步任务<IActionResult>UploadFile(ICollection 文件){...}

在我的前端,我这样调用函数:

var postSettings = {方法:'POST',凭据:'包括',模式:'cors'}上传文档(文件){var data = new FormData();data.append('文件', 文件);postSettings.body = 数据;return fetch(endPoint + '/documents/upload', postSettings);}

如果 "files" 是单个文件 - 不是包含一个文件的数组,而是单个 File 对象 - UploadFile 使用 ICollection 调用单个文件.

如果files"是文件列表,可以是 FileList 或 File 对象数组,则调用 UploadFile 时使用空的 ICollection.p>

如何提交文件列表,以便它们可以被解析为 ICollection?

解决方案

参考一次上传多个文件 - 使用 Fetch

uploadDocuments(endPoint, files) {var postSettings = {方法:'POST',凭据:'包括',模式:'cors'};var data = new FormData();如果(文件.长度> 0){for(var x = 0; x < files.length; x++) {//名称必须是文件",这样 .NET 才能正确绑定它data.append('文件', files.item(x));}}postSettings.body = 数据;return fetch(endPoint + '/documents/upload', postSettings);}

参考 使用模型绑定上传小文件

<块引用>

使用模型绑定和 IFormFile 上传文件时接口,操作方法可以接受单个 IFormFile 或一个 IEnumerable(或 List)表示几个文件.以下示例循环遍历一个或多个上传的文件,保存到本地文件系统,并返回上传文件的总数和大小.

[HttpPost][路线(文件/上传")]公共异步任务<IActionResult>发布(列出 文件){long size = files.Sum(f => f.Length);//临时位置文件的完整路径var filePath = Path.GetTempFileName();foreach (var formFile in files){如果(formFile.Length > 0){使用 (var stream = new FileStream(filePath, FileMode.Create)){等待 formFile.CopyToAsync(stream);}}}//处理上传的文件//不要依赖或信任未经验证的 FileName 属性.返回 Ok(new { count = files.Count, size, filePath});}

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

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.

If "files" is a list of files, either a FileList or an array of File objects, UploadFile is called with an empty ICollection<IFormFile>.

How do I submit a list of files in such a way that they can be parsed as an ICollection<IFormFile>?

解决方案

Reference 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 > 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 single IFormFile or an IEnumerable<IFormFile> (or List<IFormFile>) representing several files. 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});
}

这篇关于向接受 ICollection&lt;IFormFile&gt; 的 ASP.NET 控制器提交多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)