檔案上傳功能在網頁中常常出現,在ASP.NET MVC裡面要上傳檔案非常簡單,這裡簡單筆記一下有關 ASP.NET MVC 的檔案上傳基本操作方法。
- Controller
1234567891011121314151617[HttpPost]public ActionResult Upload(HttpPostedFileBase file){if (file != null && file.ContentLength > 0){var fileName = Path.GetFileName(file.FileName);var path = Server.MapPath("~/App_Data/FileUploads");//若該資料夾不存在,則新增一個if (!Directory.Exists(path)){Directory.CreateDirectory(path);}path = Path.Combine(path, fileName);file.SaveAs(path);}return RedirectToAction("Upload");} - View
12345678910111213141516@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })){<div class="form-horizontal"><div class="form-group"><label class="control-label col-sm-2">選擇檔案</label><div class="col-sm-10"><input type="file" name="file"></div></div><div class="form-group"><div class="col-sm-offset-2 col-sm-10"><input type="submit" value="提交" class="btn btn-primary" /></div></div></div>}
這邊要注意的是,如需要使用HttpPostedFileBase
上傳檔案的話,則必須添加enctype = "multipart/form-data"
,不然怎麼樣都沒辦法正常收到資料!
另外如果使用下列語法是無法接收資料的,因這樣表單並沒有含enctype = "multipart/form-data"
這項
1@using (Html.BeginForm("Upload", "Home", new { enctype = "multipart/form-data" }))
一定要用改為下面的方法
1@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))