想必很多人工作中经常需要实现上传图片的功能。
先引用此插件 http://files.cnblogs.com/files/hmYao/jquery-form.js。
前台代码
<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; } }
对应的后台代码如下:
/// <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相同。
到此结束...