在使用无刷新图片上传的时候,有三个问题需要注意:
其一,无刷新图片上传方法在后台是不能直接使用this.fuPhoto.PostedFile.SaveAs(Server.MapPath(path));
其二,在通过Ajax调用后台方法的时候,前台写入页面名称的时候,尽量保证页面命名不含有中文
其三,在使用Ajax的时候,一定要在Web.config中写入<httpHandlers><add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory,Ajax"/></httpHandlers>
下面是具体的上传方法之一:使用WebClient
前台页面:
//上传按钮 function Upload() { var ss = document.getElementById("fuPhoto").value; //获取上传文件完全名 if(ss=="") { alert('请选择上传文件'); return false; } var names=ss.split('//'); var Lname=names[names.length-1]; //获取上传文件名 var ext=Lname.split('.')[1].toLowerCase(); //获取上传文件扩展名 if(ext!= "jpg" && ext != "jepg" && ext != "bmp" && ext != "gif") { alert('请选择JPG,JEPG,BMP,GIF格式的照片文件'); return false; } var str = UpLoadUserPhoto.UploadFile(ss,ext).value; if(str!="") { window.location="UpLoadUserPhoto.aspx?Imgurl=" + str; } }
后台页面:
protected void Page_Load(object sender, EventArgs e) { Ajax.Utility.RegisterTypeForAjax(typeof(UpLoadUserPhoto));}
[Ajax.AjaxMethod] //前台保存方法 public string UploadFile(string filePath, string enm) { string strpath = "~/图片上传预览截取保存/UploadPhoto/" + DateTime.Now.ToString("yyyyMMddhhmmss") + "." + enm; string SaveUrl = Server.MapPath(strpath);//上传到什么位置 WebClient myWebClient = new WebClient();//创建WebClient实例 myWebClient.Credentials = CredentialCache.DefaultCredentials;//得到网络凭据 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs); byte[] postArray = r.ReadBytes((int)fs.Length); Stream postStream = myWebClient.OpenWrite(SaveUrl, "PUT"); postStream.Write(postArray, 0, postArray.Length); postStream.Close(); return Server.UrlEncode(strpath); } 注意:需要引用 using System.Net;
