来自于:Darren Ji
    本篇体验在控制器方法中使用controllerContext.HttpContext.Request.Files上传多个文件。

    控制器:

    1. using System;
    2. using System.Collections.Generic;
    3. using System.IO;
    4. using System.Linq;
    5. using System.Web;
    6. using System.Web.Mvc;
    7. namespace MvcApplication2.Controllers
    8. {
    9. public class HomeController : Controller
    10. {
    11. public ActionResult Index()
    12. {
    13. return View();
    14. }
    15. public ActionResult FileUploads()
    16. {
    17. string pathForSaving = Server.MapPath("~/Uploads");
    18. if (this.CreateFolderIfNeeded(pathForSaving))
    19. {
    20. foreach (string file in Request.Files)
    21. {
    22. HttpPostedFileBase uploadFile = Request.Files[file] as HttpPostedFileBase;
    23. if (uploadFile != null && uploadFile.ContentLength > 0)
    24. {
    25. var path = Path.Combine(pathForSaving, uploadFile.FileName);
    26. uploadFile.SaveAs(path);
    27. }
    28. }
    29. }
    30. return RedirectToAction("Index");
    31. }
    32. // 检查是否要创建上传文件夹
    33. private bool CreateFolderIfNeeded(string path)
    34. {
    35. bool result = true;
    36. if (!Directory.Exists(path))
    37. {
    38. try
    39. {
    40. Directory.CreateDirectory(path);
    41. }
    42. catch (Exception)
    43. {
    44. //TODO:处理异常
    45. result = false;
    46. }
    47. }
    48. return result;
    49. }
    50. }
    51. }

    Home/Index.cshtml视图:

    1. @{
    2. ViewBag.Title = "Index";
    3. Layout = "~/Views/Shared/_Layout.cshtml";
    4. }
    5. @using (Html.BeginForm("FileUploads", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    6. {
    7. <input type="file" name="files1" id="file1" /><br/>
    8. <input type="file" name="files2" id="file2" /><br/>
    9. <input type="file" name="files3" id="file3" /><br/>
    10. <input type="submit" value="同时上传多个文件" />
    11. }

    注意:name属性值可以不同