想必不少人工做中常常須要實現上傳圖片的功能。jquery
先引用此插件 http://files.cnblogs.com/files/hmYao/jquery-form.js。ajax
前臺代碼ide
<form data-ajax-success="AfterUpload" enctype="multipart/form-data" id="frm"> <input type="file" name="fileBase" value=" " id="imgUpload" class="jiangli_1_w" /> <input type="submit" id="btnSub" value="上傳圖片" /> <span class="flat_loe">上傳圖片寬度最大尺寸720px,高度無限制</span> </form>
//上傳圖片 $("#btnSub").click(function () { $("#frm").ajaxSubmit({ url: "/Slide/UploadImage", type: "Post", success: AfterUpload }); return false; }); function AfterUpload(msg) { if (msg != "0") { $("#imgPath").removeAttr("src").attr("src", msg); } else { swal({ title: "舒適提示", text: "圖片格式有誤" }); $("#imgPath").val(""); return false; } }
對應的後臺代碼以下:url
/// <summary> /// 上傳圖片 /// </summary> /// <param name="fileBase"></param> /// <returns></returns> [HttpPost] public ActionResult UploadImage(HttpPostedFileBase fileBase) { string imgurl = string.Empty; string imgPath = System.IO.Path.GetFileName(fileBase.FileName); int index = imgPath.LastIndexOf('.'); string suffix = imgPath.Substring(index).ToLower(); if (suffix == ".jpg" || suffix == ".jpeg" || suffix == ".png" || suffix == ".gif" || suffix == ".bmp") { string pictureName = DateTime.Now.Ticks.ToString() + suffix; //圖片名稱 string savePath = Server.MapPath("/Files/Images/SlideConfig/");//幻燈片文件夾 if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } imgurl = "http://" + Request.Url.Authority + "//Files/Images/SlideConfig/" + pictureName; fileBase.SaveAs(savePath + pictureName); } else { imgurl = "0"; } return Content(imgurl); }
有一點很重要,不少人都拿不到上傳的路徑值。注意參數的名稱 須要和 file標籤的name相同。spa
到此結束...插件