第一步:視圖方法 @using (Html.BeginForm("StoreRegist", "Register", FormMethod.Post, new { enctype = "multipart/form-data" })) 第二步:控件 <input type="file" border="0" name="files" id="portrait_Z" onchange="previewImage(this)" value="上傳身份證正面照" /> <input type="file" border="0" name="files" id="portrait_F" onchange="previewImage(this)" value="上傳身份證反面照" /> 注意:name名稱要相同 第三步:控制器 public ActionResult StoreRegist(StoreRegisterModels model, string ReturnUrl, IEnumerable<HttpPostedFileBase> files) 核心代碼: if (files.Count() > 0) { foreach (HttpPostedFileBase file in files) { var supportedTypes = new[] { "jpg", "jpeg", "png", "gif", "bmp" }; var fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1); if (!supportedTypes.Contains(fileExt)) { return Json(new { msg = -1 }); } if (file.ContentLength > 1024 * 1000 * 10) { return Json(new { msg = -2 }); } Random r = new Random(); var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + r.Next(10000) + "." + fileExt;//給文件命名,以時間格式命名 var filepath = Path.Combine(Server.MapPath(Sys.Core.Map.Pic + "/Images/IDNumImg"), filename);//獲取路徑 file.SaveAs(filepath);//上傳到服務(wù)器 //return Json(new { msg = filename }); } } 絢爺20150328工作總結(jié) |
|