有时候我们需要上传图片时不刷新页面,那么Ajax就是很好的东西哦。之前在网上找了很多的资料都不对,不是这里就是那里错,这是本人亲自测试了的哈,是没有问题的,若有不足之处希望指正。我用的.net,对了这里还需要引用Jquery跟Jquery.form.js两个文件,没看到上传附件在哪里咯,需要的朋友可以给我留言哈
前台代码 Default2.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="admin/js/jquery.js" type="text/javascript"></script> <script src="admin/js/jquery.form.js" type="text/javascript"></script> <script type="text/javascript"> function TajaxFileUpload() { var imgname = $.trim($("#File1").val()); if (imgname != "") { $("#form1").ajaxSubmit({ success: function (html, status) { if (status == "success") { var json = eval('(' + html + ')'); if (json.state == "success") { //上传成功 alert("上传成功!"); } else { alert(json.msg + "上传失败!"); } } }, error: function (error) { alert(error); }, url: 'admin/ajax/upload.ashx', /*设置post提交到的页面*/ type: "post", /*设置表单以post方法提交*/ dataType: "text" /*设置返回值类型为文本*/ }); } else { alert("请上传图片!"); return false; } } </script> </head> <body> <form id="form1" runat="server"> <div> <input id="File1" type="file" name="picture" /> <input type="button" value="上 传" onclick="TajaxFileUpload()" /> </div> </form> </body> </html>
Ajax页面代码 upload.ashx
<%@ WebHandler Language="C#" Class="upload" %> using System; using System.Web; using System.IO; using System.Text; using System.Net; public class upload : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; try { string time = DateTime.Now.ToString("yyyyMMdd").Trim(); string fileName = time; HttpPostedFile pic = context.Request.Files["picture"]; string foldPath = HttpContext.Current.Server.MapPath("~/UploadFile/") + fileName+"\"; //foldPath = foldPath + fileName; DirectoryInfo di = new DirectoryInfo(foldPath); if (!di.Exists)//如果文件夹目录不存在 { di.Create();//新建文件夹 } string imageName = UpLoadImage(pic, foldPath); context.Response.Write("{state:'success',msg:'上传成功:" + imageName + "'}"); } catch (Exception ex) { context.Response.Write("{state:'error',msg:'" + ex.Message + "'}"); } } #region 上传图片 /// <summary> /// 上传图片 /// </summary> /// <param name="imgfile">文件http流</param> /// <param name="nowpath">所需放置的文件路径</param> /// <returns>上传成功,返回字符串,否则,抛出异常</returns> public static string UpLoadImage(HttpPostedFile imgfile, string nowpath) { try { string serverPath = System.Web.HttpContext.Current.Server.MapPath("~"); string toFilePath = Path.Combine(serverPath, nowpath); //获取要保存的文件信息 FileInfo file = new FileInfo(imgfile.FileName); //获得文件扩展名 string fileNameExt = file.Extension; //验证合法的文件 if (CheckImageExt(fileNameExt)) { //生成将要保存的随机文件名 string fileName = DateTime.Now.ToString("yyyyMMddHHmmss").Trim() + 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 imgfile.SaveAs(toFile); string relativePath = fileName; return relativePath; } else { throw new Exception("文件格式非法,请上传gif|jpg|bmp|png格式的文件。"); } } catch { throw; } } #endregion #region 图片上传格式和文件名 /// <summary> /// 检查是否为合法的上传图片 /// </summary> /// <param name="_fileExt"></param> /// <returns></returns> public static bool CheckImageExt(string _ImageExt) { string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg", ".bmp", ".png" }; for (int i = 0; i < allowExt.Length; i++) { if (string.Compare(allowExt[i], _ImageExt, true) == 0) { return true; } } return false; } private static 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 public bool IsReusable { get { return false; } } }
最后上传的图片的保存路径效果图如下: