遍历HttpFileCollection为何获取HttpPostedFile而非HttpPostedFileBase?
转换说明
HttpFileCollection 索引器返回的是 HttpPostedFile 类型,该类型未继承 HttpPostedFileBase 抽象类,无法直接隐式或强制转换。ASP.NET 内置了适配类 HttpPostedFileWrapper,该类继承自 HttpPostedFileBase,可通过构造函数传入 HttpPostedFile 实例完成类型适配。
实现代码
基础遍历写法
using System.Collections.Generic; using System.Web; public List<HttpPostedFileBase> GetFiles() { HttpFileCollection files = HttpContext.Current.Request.Files; List<HttpPostedFileBase> result = new List<HttpPostedFileBase>(); foreach (string fileName in files) { HttpPostedFile originalFile = files[fileName]; HttpPostedFileBase castedFile = new HttpPostedFileWrapper(originalFile); // 过滤未选择文件的空上传项(可选) if (castedFile.ContentLength > 0) { result.Add(castedFile); } } return result; }
LINQ 简化写法
如果项目支持LINQ,可以用更简洁的写法实现:
using System.Collections.Generic; using System.Linq; using System.Web; public List<HttpPostedFileBase> GetFiles() { return HttpContext.Current.Request.Files .Cast<string>() .Select(fileName => new HttpPostedFileWrapper(HttpContext.Current.Request.Files[fileName])) .Where(file => file.ContentLength > 0) .ToList(); }
注意事项
HttpPostedFileWrapper定义在System.Web程序集中,使用前请确认项目已引用该程序集,并引入System.Web命名空间。- 前端文件上传表单中,未选择文件的表单项会生成
ContentLength为0的空对象,建议增加过滤逻辑避免无效项进入结果集。
内容的提问来源于stack exchange,提问作者Greg
相关产品推荐
相关产品推荐

