在asp.net mvc项目中,使用c#处理多文件批量上传主要依赖前端multiple选择和后端HttpPostedFileBase数组接收。下面直接说明具体实现方式。

前端表单如何实现多文件选择
在视图中,使用<input type="file" multiple>即可让用户一次选多个文件,表单必须设置enctype="multipart/form-data"。
<form action="/Upload/Multiple" method="post" enctype="multipart/form-data"> <input type="file" name="files" multiple /> <button type="submit">上传</button> </form>
后端控制器接收与保存文件
控制器动作使用HttpPostedFileBase[]参数接收,框架会自动绑定同名files字段。遍历数组即可逐个保存到服务器目录。
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
public class UploadController : Controller
{
// 接收多文件批量上传
[HttpPost]
public ActionResult Multiple(HttpPostedFileBase[] files)
{
if (files != null && files.Length > 0)
{
// 定义保存根目录
string root = Server.MapPath("~/Uploads/");
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
foreach (HttpPostedFileBase file in files)
{
if (file != null && file.ContentLength > 0)
{
// 生成唯一文件名避免覆盖
string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
string path = Path.Combine(root, fileName);
file.SaveAs(path);
}
}
return Content("上传成功");
}
return Content("未选择文件");
}
}
配置文件大小与数量限制
默认asp.net限制上传文件大小为4MB,多文件总大小也容易超限。在web.config中调整maxRequestLength与maxAllowedContentLength。
<configuration>
<system.web>
<!-- 单位KB,此处设为50MB -->
<httpRuntime maxRequestLength="51200" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!-- 单位字节,此处设为50MB -->
<requestLimits maxAllowedContentLength="52428800" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
基础校验建议
- 检查文件扩展名,限制可执行文件上传
- 校验ContentLength防止空文件
- 对单文件大小分别判断,避免单个过大
通过上述方式,c#多文件批量上传功能即可稳定落地,满足大多数后台管理系统的附件提交场景。
c#多文件批量上传HttpPostedFileBase修改时间:2026-07-27 01:03:18