ajax图片上传,图片异步上传,更新实例
最近在研究ajax图片上传,图片异步上传,更新,留作参考。
直接上源码吧:
js源码:
///<referencepath="jquery-1.8.3.js"/> ///<referencepath="ajaxForm/jquery.form.js"/> /*! *jQueryupload *用于上传单个文件,上传成功后,返回文件路径。 *本插件依赖jQuery,jquery.form请在使用时引入依赖的文件 * *Date:2014/4/23 */ /* <divstyle="width:100%;float:left;"> <inputtype="hidden"id="hfThumbnail"value="/uploads/2014/04/23/635338686611432716.jpg"/> <divclass="imgdiv"></div> <spanclass="img_span"> <inputtype="file"name="file"/> </span> <inputtype="button"value="上传"class="upload"/> </div> <divstyle="width:100%;float:left;"> <inputtype="hidden"id="hfThumbnail"value="/uploads/2014/04/23/635338686611432716.jpg"/> <divclass="imgdiv"></div> <spanclass="img_span"> <inputtype="file"name="file"/> </span> <inputtype="button"value="上传"class="upload"/> </div>
js:
$(document).ready(function(){ //$(".upload").upload({ //uploadData:{id:"12233"}, //successFn:function(response,statusText,xhr,$this){ //alert(response.Data.RelativePath) //}, //deleteData:{id:function(){return"asdfasdf"}} //}); $(".upload").upload({ uploadData:{id:"12233"}, successFn:"success",//可以是字符串 deleteData:{id:function(){return"asdfasdf"}} }); }); //上传成功后执行该函数 functionsuccess(response,statusText,xhr,$this){ //比如插入编辑器 alert(response.Data.RelativePath+$this.attr("value")) } */ (function($){ $.extend($.fn,{ upload:function(settings){ varoptions=$.extend({ fileType:"gif|jpg|jpeg|png|bmp",//允许的文件格式 uploadUrl:"/ajax/handler.ashx?action=uploadfile",//上传URL地址 deleteUrl:"/ajax/handler.ashx?action=deletefile",//删除URL地址 width:"",//图片显示的宽度 height:100,//图片显示的高度 imgSelector:".imgdiv",//图片选择器 uploadData:{},//上传时需要附加的参数 deleteData:{},//删除时需要附加的参数 deleteFn:function($parent,showMessage){//删除图片的方法(默认方法使用POST提交) methods.deleteImage($parent,showMessage); }, beforeSubmitFn:"beforeUpload",//上传前执行的方法原型beforeSubmit(arr,$form,options); successFn:"uploadSuccess",//上传成功后执行的方法uploadSuccess(response,statusText,xhr,$this) errorFn:"uploadError"//上传失败后执行的方法 },settings); //上传准备函数 varmethods={ //验证文件格式 checkFile:function(filename){ varpos=filename.lastIndexOf("."); varstr=filename.substring(pos,filename.length); varstr1=str.toLowerCase(); if(typeofoptions.fileType!=='string'){options.fileType="gif|jpg|jpeg|png|bmp";} varre=newRegExp("\.("+options.fileType+")$"); returnre.test(str1); }, //创建表单 createForm:function(){ var$form=document.createElement("form"); $form.action=options.uploadUrl; $form.method="post"; $form.enctype="multipart/form-data"; $form.style.display="none"; //将表单加当document上, document.body.appendChild($form);//创建表单后一定要加上这句否则得到的form不能上传。document后要加上body,否则火狐下不行。 return$($form); }, //创建图片 createImage:function(){ //不能用newImage()来创建图片,否则ie下不能改变img的宽高 varimg=$(document.createElement("img")); img.attr({"title":"双击图片可删除图片!"}); if(options.width!==""){ img.attr({"width":options.width}); } if(options.height!==""){ img.attr({"height":options.height}); } returnimg; }, showImage:function(filePath,$parent){ var$img=methods.createImage(); $parent.find(options.imgSelector).find("img").remove(); //要先append再给img赋值,否则在ie下不能缩小宽度。 $img.appendTo($parent.find(options.imgSelector)); $img.attr("src",filePath); this.bindDelete($parent); }, bindDelete:function($parent){ $parent.find(options.imgSelector).find("img").bind("dblclick",function(){ options.deleteFn($parent,true); }); }, deleteImage:function($parent,showMessage){ var$fileInput=$parent.find("input:hidden"); if($fileInput.val()!==""){ vardata=$.extend(options.deleteData,{filePath:$fileInput.val(),t:Math.random()}); $.post(options.deleteUrl,data,function(response){ if(showMessage){alert(response.MessageContent)} if(response.MessageType==1){ $fileInput.val(""); $parent.find(options.imgSelector).find("img").remove(); } },"JSON"); } }, onload:function($parent){ varhiddenInput=$parent.find("input:hidden"); if(typeofhiddenInput!=="undefined"&&hiddenInput.val()!==""){ varimg=methods.createImage(); if($parent.find(options.imgSelector).find("img").length>0){$parent.find(options.imgSelector).find("img").remove();} //要先append再给img赋值,否则在ie下不能缩小宽度。 img.appendTo($parent.find(options.imgSelector)); img.attr("src",hiddenInput.val()); methods.bindDelete($parent); } } }; //上传主函数 this.each(function(){ var$this=$(this); methods.onload($this.parent()); $this.bind("click",function(){ var$fileInput=$(this).parent().find("input:file"); varfileBox=$fileInput.parent(); if($fileInput.val()===""){ alert("请选择要上传的图片!"); returnfalse; } //验证图片 if(!methods.checkFile($fileInput.val())){ alert("文件格式不正确,只能上传格式为:"+options.fileType+"的文件。"); returnfalse; } //若隐藏域中有图片,先删除图片 if($fileInput.val()!==""){ options.deleteFn($this.parent(),false); //methods.deleteImage($this.parent(),false); } //创建表单 var$form=methods.createForm(); //把上传控件附加到表单 $fileInput.appendTo($form); fileBox.html("<imgsrc=\"/admin/styles/images/loading.gif\"/>正在上传..."); $this.attr("disabled",true); //构建ajaxSubmit参数 vardata={}; data.data=options.uploadData; data.type="POST"; data.dataType="JSON"; //上传前 data.beforeSubmit=function(arr,$form,options){ varbeforeSubmitFn; try{beforeSubmitFn=eval(options.beforeSubmitFn)}catch(err){}; if(beforeSubmitFn){ var$result=beforeSubmitFn(arr,$form,options); if(typeof($result)=="boolean") return$result; } }; //上传失败 data.error=function(response,statusText,xhr,$form){ varerrorFn; try{errorFn=eval(options.errorFn)}catch(err){}; if(errorFn){ errorFn(response.responseText,statusText,xhr,$this); } }; //上传成功 data.success=function(response,statusText,xhr,$form){ //response=eval("("+response+")"); if(response.MessageType==1){ methods.showImage(response.Data.RelativePath,$this.parent()); $this.parent().find("input:hidden").val(response.Data.RelativePath); varsuccessFn; try{successFn=eval(options.successFn)}catch(err){}; if(successFn){ $.ajaxSetup({cache:false});//这个不能少,否则ie下会提示下载 successFn(response,statusText,xhr,$this); } }else{ alert(response.MessageContent); } $this.attr("disabled",false); fileBox.html("<inputtype=\"file\"name=\"file\"/>"); $form.remove(); }; try{ //开始ajax提交表单 $form.ajaxSubmit(data); }catch(e){ alert(e.message); } }); }); } }); })(jQuery)
html代码:
<!DOCTYPEhtml> <htmlxmlns="http://www.w3.org/1999/xhtml"> <headrunat="server"> <metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/> <scriptsrc="Scripts/jquery/jquery-1.8.3.js"></script> <scriptsrc="Scripts/jquery/ajaxForm/jquery.form.js"></script> <scriptsrc="Scripts/jquery/jquery.upload.js"></script> <title></title> </head> <body> <formid="form1"runat="server"> <divstyle="width:100%;float:left;"> <inputtype="hidden"id="hfThumbnail"value="/uploads/2014/04/23/635338686611432716.jpg"/> <divclass="imgdiv"></div> <spanclass="img_span"> <inputtype="file"name="file"/> </span> <inputtype="button"value="上传"class="upload"/> </div> <divstyle="width:100%;float:left;"> <inputtype="hidden"id="hfThumbnail"value="/uploads/2014/04/23/635338686611432716.jpg"/> <divclass="imgdiv"></div> <spanclass="img_span"> <inputtype="file"name="file"/> </span> <inputtype="button"value="上传"class="upload"/> </div> </form> <scripttype="text/javascript"> $(document).ready(function(){ //$(".upload").upload({ //uploadData:{id:"12233"}, //successFn:function(response,statusText,xhr,$this){ //alert(response.Data.RelativePath) //}, //deleteData:{id:function(){return"asdfasdf"}} //}); $(".upload").upload({ uploadData:{id:"12233"}, successFn:"success", deleteData:{id:function(){return"asdfasdf"}} }); }); //上传成功后执行该函数 functionsuccess(response,statusText,xhr,$this){ //比如插入编辑器 alert(response.Data.RelativePath+$this.attr("value")) } </script> </body> </html>
服务器端使用一般处理程序:
publicvoidProcessRequest(HttpContextcontext) { context.Response.ContentType="application/json"; varaction=context.Request.QueryString.Get<string>("action").ToLower(); varresponse=newJsonResult(StatusMessageType.Error,"没有权限或无效请求。").ToJson(); switch(action) { case"uploadfile": if(context.Request.Files.Count>0) response=UploadFile(context.Request); break; case"deletefile": response=DeleteFile(context.Request.Form); break; default: break; } context.Response.Write(response); } ///<summary> /// ///</summary> ///<paramname="file"></param> ///<returns></returns> privatestringUploadFile(HttpRequestrequest) { if(request.Files.Count==0) returnnewJsonResult(StatusMessageType.Error,"没有可处理的数据。").ToJson(); varid=request.Form.Get<string>("id",""); varfile=request.Files[0]; if(file==null||file.ContentLength<=0||string.IsNullOrEmpty(file.FileName)) returnnewJsonResult(StatusMessageType.Error,"没有可处理的数据。").ToJson(); //IStoreFilestoreFile=null; string[]datePaths=newstring[]{"~/uploads/"}; datePaths=datePaths.Union(DateTime.Now.ToString("yyyy-MM-dd").Split('-')).ToArray(); varrelativePath=storeProvider.JoinDirectory(datePaths); vardirPath=HttpContext.Current.Server.MapPath(relativePath); if(!System.IO.Directory.Exists(dirPath)) System.IO.Directory.CreateDirectory(dirPath); varfileName=GenerateFileName(Path.GetExtension(file.FileName)); varfilePath=Path.Combine(dirPath,fileName); file.SaveAs(filePath); returnnewJsonResult(StatusMessageType.Success,"上传成功。",new { RelativePath=WebUtility.ResolveUrl(Path.Combine(relativePath,fileName)), Size=file.ContentLength, Id=id, }).ToJson(); } publicstringDeleteFile(NameValueCollectionform) { varfilePath=form.Get<string>("filePath","").Trim(); if(string.IsNullOrEmpty(filePath)) returnnewJsonResult(StatusMessageType.Error,"无效提交。").ToJson(); try { if(System.IO.File.Exists(HttpContext.Current.Server.MapPath(filePath))) { System.IO.File.Delete(HttpContext.Current.Server.MapPath(filePath)); returnnewJsonResult(StatusMessageType.Success,"文件删除成功。").ToJson(); } else { returnnewJsonResult(StatusMessageType.Success,"找不到该文件。").ToJson(); } } catch(Exception) { returnnewJsonResult(StatusMessageType.Hint,"发生错误。").ToJson(); } } ///<summary> ///生成随机文件名 ///</summary> ///<returns></returns> privatestringGenerateFileName(stringextension) { returnDateTime.Now.Ticks.ToString()+extension; }
程序使用的是framework4.0,所以使用了一些扩展方法。
JsonTesult类代码:
[Serializable] publicclassJsonResult { privateStatusMessageType_messageType; privatestring_messageContent; ///<summary> /// ///</summary> ///<paramname="messageType"></param> ///<paramname="messageContent"></param> ///<paramname="data"></param> publicJsonResult(StatusMessageTypemessageType,stringmessageContent,objectdata=null) { _messageType=messageType; _messageContent=messageContent; Data=data; } publicStatusMessageTypeMessageType { get{return_messageType;} set{_messageType=value;} } publicstringMessageContent { get{return_messageContent;} set{_messageContent=value;} } publicobjectData{get;set;} publicstringToJson() { JavaScriptSerializerserializer=newJavaScriptSerializer(); varjson=serializer.Serialize(this); //stringp=@"\\/Date(\d+)\\/"; //MatchEvaluatormatchEvaluator=newMatchEvaluator(ConvertJsonDateToDateString); //Regexreg=newRegex(p); //json=reg.Replace(json,matchEvaluator); returnjson; } privatestaticstringConvertJsonDateToDateString(Matchm) { stringresult=string.Empty; DateTimedt=newDateTime(1970,1,1); dt=dt.AddMilliseconds(long.Parse(m.Groups[1].Value)); dt=dt.ToLocalTime(); result=dt.ToString("d"); returnresult; } }
StatusMessageType枚举类:
///<summary> ///提示消息类别 ///</summary> publicenumStatusMessageType { ///<summary> ///权限不足 ///</summary> NoAccess=-2, ///<summary> ///错误 ///</summary> Error=-1, ///<summary> ///成功 ///</summary> Success=1, ///<summary> ///提示信息 ///</summary> Hint=0 }
其他的扩展方法就不一一给出来了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。