一、html頁面如下
1 <div id="container"> 2 <form id="myForm"> 3 <p class="img_P"><img id="previewPic" name="previewPic" /></p> 4 <p><input type="file" id="imgUpload" name="imgUpload" /></p> 5 <p><button id="submitBtn" type="button" value="提交">提交</button></p> 6 </form> 7 </div>
二、實現上傳圖片預覽功能
1 $(function () { 2 $('#imgUpload').on('change', function () { 3 var file = this.files[0]; 4 if(this.files&&file) 5 { 6 var reader = new FileReader(); 7 reader.onload = function (e) { 8 $('#previewPic').attr('src', e.target.result); 9 } 10 reader.readAsDataURL(file); 11 } 12 }) 13 })
三、將圖片傳到后台(圖片存儲到固定文件夾下)
view頁面的代碼如下(頁面需引用jquery和jquery.form.js兩個文件):
1 $('#submitBtn').on('click', function () { 2 $('#myForm').ajaxSubmit({ 3 type: 'post', 4 url: '/Form/ImgSubmit', 5 success: function (data) { 6 } 7 }) 8 })
Controller代碼
1 [HttpPost] 2 public ActionResult ImgSubmit() 3 { 4 if (Request.Files.Count>0) 5 { 6 string extension = string.Empty; 7 HttpPostedFileBase file = Request.Files[0] as HttpPostedFileBase; 8 if (file.FileName.Length > 0) 9 { 10 if (file.FileName.IndexOf('.') > -1) 11 { 12 //原來也可以這用獲取擴展名 13 //extension = file.FileName.Remove(0, file.FileName.LastIndexOf('.')); 14 string filePath = "/Upload/"; 15 //創建路徑 16 CreateFilePath(filePath); 17 if (file.FileName.ToString() != "") 18 { 19 string absoluteSavePath = System.Web.HttpContext.Current.Server.MapPath("~" + filePath); 20 var pathLast = Path.Combine(absoluteSavePath, file.FileName); 21 file.SaveAs(pathLast); 22 } 23 } 24 } 25 } 26 return Content("success"); 27 } 28 29 /// <summary> 30 /// 當存儲的文件路徑不存在時,創建文件路徑 31 /// </summary> 32 /// <param name="savePath">保存路徑(非絕對路徑)</param> 33 public static void CreateFilePath(string savePath) 34 { 35 string Absolute_savePath = System.Web.HttpContext.Current.Server.MapPath("~" + savePath); 36 if (!Directory.Exists(Absolute_savePath)) 37 Directory.CreateDirectory(Absolute_savePath); 38 }
注:在做的過程中,遇到了上傳了圖片,但是后台總是接收不到(Request.Files.Count總是為0),原因可能如下:
1、<form> 不能被嵌套(一個頁面可以有多個form,但是不能被嵌套)
2、<form method="post" ,enctype="multipart/form-data" ></form>
3、<input type="file" id="imgUpload" name="imgUpload" /> 一定要有name屬性