.NET MVC 上傳檔案
阿新 • • 發佈:2019-01-30
@{ ViewBag.Title = "Index"; } <form action="" method="post" enctype="multipart/form-data"> <label for="file1">Filename:</label> <input type="file" name="files" id="file1" /> <label for="file2">Filename:</label> <input type="file" name="files" id="file2" /> <input type="submit" /> </form>
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace XCX_DataApi.Areas.Module00001.Controllers { public class FileUpLoadController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(IEnumerable<HttpPostedFileBase> files) { foreach (var k in files) { if (k != null) { if (k.ContentLength > 0) { var fileName = Path.GetFileName(k.FileName); string folderPath = Server.MapPath("~") + "\\" + "UploadFiles"; if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } var path = Path.Combine(folderPath, fileName); k.SaveAs(path); } } } return RedirectToAction("Index"); } } }