MVC+Jquery局部刷新上传图片
做了一个简单的MVC局部刷新上传图片的例子来分享一下,希望能对大家有所帮助
1、先看一下http://malsup.com/jquery/form/网站因为我们做此项目要用到此提供的一个jquery.form.js文件,里面提供了api过于ajax局部刷新的知识
2、建一个MVC项目将jquery.form.js加入的javascript文件中
3、写一个PicUploadHander类继承IHttpHandler
public class PicUploadHander : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //验证上传的权限TODO string _fileNamePath = ""; try { _fileNamePath = context.Request.Files[0].FileName; //开始上传 string _savedFileResult = UpLoadImage(_fileNamePath, context); context.Response.Write(_savedFileResult); } catch { context.Response.Write("上传提交出错"); } } public string UpLoadImage(string fileNamePath, HttpContext context) { try { string serverPath = System.Web.HttpContext.Current.Server.MapPath("~"); string toFilePath = Path.Combine(serverPath, @"Content\Upload\Images\"); //获取要保存的文件信息 FileInfo file = new FileInfo(fileNamePath); //获得文件扩展名 string fileNameExt = file.Extension; //验证合法的文件 if (CheckImageExt(fileNameExt)) { //生成将要保存的随机文件名 string fileName = GetImageName() + fileNameExt; //获得要保存的文件路径 string serverFileName = toFilePath + fileName; //物理完整路径 string toFileFullPath = serverFileName; //HttpContext.Current.Server.MapPath(toFilePath); //将要保存的完整文件名 string toFile = toFileFullPath;//+ fileName; ///创建WebClient实例 WebClient myWebClient = new WebClient(); //设定windows网络安全认证 方法1 myWebClient.Credentials = CredentialCache.DefaultCredentials; ////设定windows网络安全认证 方法2 context.Request.Files[0].SaveAs(toFile); string relativePath = System.Web.HttpContext.Current.Request.ApplicationPath + string.Format(@"Content/Upload/Images/{0}", fileName); return relativePath; } else { throw new Exception("文件格式非法,请上传gif或jpg格式的文件。"); } } catch (Exception ex) { return ex.Message; } } public bool IsReusable { get { return false; } } #region Private Methods /// <summary> /// 检查是否为合法的上传图片 /// </summary> /// <param name="_fileExt"></param> /// <returns></returns> private bool CheckImageExt(string _ImageExt) { string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg", ".bmp" }; for (int i = 0; i < allowExt.Length; i++) { if (allowExt[i] == _ImageExt) { return true; } } return false; } private string GetImageName() { Random rd = new Random(); StringBuilder serial = new StringBuilder(); serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff")); serial.Append(rd.Next(0, 999999).ToString()); return serial.ToString(); } #endregion
4、index.cshtml
@{ ViewBag.Title = "Index"; } <h2>Index</h2> <script type="text/javascript"> $(function () { //上传图片 $("#btnUpload").click(function () { if ($("#flUpload").val() == "") { alert("请选择一个图片文件,再点击上传。"); return; } $('#UpLoadForm').ajaxSubmit({ success: function (html, status) { var result = html.replace("<pre>", ""); result = result.replace("</pre>", ""); $("#image").attr('src', result); alert(result); } }); }); }); </script> <form id ="form"> <p> <img id="image" style="width: 200px; height:200px;" /></p></form> <form id="UpLoadForm" name="UpLoadForm" method="post" enctype="multipart/form-data" action='@Url.Content("~/Utility/PicUploadHander.ashx")'> <table border="0" cellpadding="0" cellspacing="0" class="upp"> <tr> <td> <input class="width120" type="file" id="flUpload" name="flUpload" /> <input id="btnUpload" type="button" value="上传" /> </td> </tr> </table> </form>