最近用到了文件上傳功能,下面給出ASP.NET MVC文件上傳的一個簡單示例:
一、前端代碼
@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new {enctype = "multipart/form-data"})) { <div>文件上傳:<input type="file" name="myFile"/></div> <input type="submit" value="提交"/> }
二、后台代碼
/// <summary> /// 上傳文件 /// </summary> /// <returns>上傳文件結果信息</returns> [HttpPost] public ActionResult UploadFile() { HttpPostedFileBase file = Request.Files["myFile"]; if (file != null) { try { var filename = Path.Combine(Request.MapPath("~/Upload"), file.FileName); file.SaveAs(filename); return Content("上傳成功"); } catch (Exception ex) { return Content(string.Format("上傳文件出現異常:{0}", ex.Message)); } } else { return Content("沒有文件需要上傳!"); } }