来自于:Darren Ji
本篇体验在控制器方法中使用controllerContext.HttpContext.Request.Files上传多个文件。
控制器:
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Web;using System.Web.Mvc;namespace MvcApplication2.Controllers{public class HomeController : Controller{public ActionResult Index(){return View();}public ActionResult FileUploads(){string pathForSaving = Server.MapPath("~/Uploads");if (this.CreateFolderIfNeeded(pathForSaving)){foreach (string file in Request.Files){HttpPostedFileBase uploadFile = Request.Files[file] as HttpPostedFileBase;if (uploadFile != null && uploadFile.ContentLength > 0){var path = Path.Combine(pathForSaving, uploadFile.FileName);uploadFile.SaveAs(path);}}}return RedirectToAction("Index");}// 检查是否要创建上传文件夹private bool CreateFolderIfNeeded(string path){bool result = true;if (!Directory.Exists(path)){try{Directory.CreateDirectory(path);}catch (Exception){//TODO:处理异常result = false;}}return result;}}}
Home/Index.cshtml视图:
@{ViewBag.Title = "Index";Layout = "~/Views/Shared/_Layout.cshtml";}@using (Html.BeginForm("FileUploads", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })){<input type="file" name="files1" id="file1" /><br/><input type="file" name="files2" id="file2" /><br/><input type="file" name="files3" id="file3" /><br/><input type="submit" value="同时上传多个文件" />}
注意:name属性值可以不同
