asp.net mvc 多文件上传
@{ ViewBag.Title = "多文件上传测试"; } <h2>多文件上传测试</h2> <form action="/Demo/Index" method="post" enctype="multipart/form-data"> <input type="file" /><br /> <input type="file" /><br /> <input type="file" /><br /> <input type="submit" value="上传" /> </form>
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using ZhaoWoAPI.Models; namespace ZhaoWoAPI.Controllers { public class DemoController : Controller { [HttpPost] public ActionResult Index(string content) { try { FileLogModel.Log("========================开始上传图片=====================:content=" + content); HttpFileCollectionBase files = Request.Files; FileLogModel.Log("==================上传图片数量为:" + files.Count+"==========================="); if(files.Count<=0) { FileLogModel.Log("=================无上传图片===================================" ); return Content("0"); } for (int i = 0; i < files.Count; i++) { HttpPostedFileBase hpf = files[i]; if (hpf.ContentLength <= 0) { continue; } var extension = Path.GetExtension(hpf.FileName); FileLogModel.Log("=====================文件后缀名:"+extension+"=========================="); string datename = DateTime.Now.ToString("yyyy-MM-dd"); string path = Server.MapPath("/Resource/SendInfo/" + datename + "/"); FileLogModel.Log("=====================上传路径:" + path + "=========================="); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string newfilename = path + ZhaoWoCommon.GUIDTools.GetGUID() + extension; FileLogModel.Log("=====================完整路径:" + newfilename + "=========================="); hpf.SaveAs(newfilename); } FileLogModel.Log("=====================上传成功==========================" ); return Content("ok"); } catch (Exception ex) { FileLogModel.Log("上传失败"+ex.Message ); return Content("error"); } } public ActionResult Test() { return View(); } } }