功能实现
代码功能 图片截取 返回上次访问位置 退出登录 找回密码邮件
1 图片截取,使用jquery.imgareaselect.min.js
1 <%@ Page Title="" Language="C#" MasterPageFile="~/Master/UserMaster.Master" AutoEventWireup="true" CodeBehind="UserCenter.aspx.cs" Inherits="Maticsoft.Web.UserInfoManager.UserCenter" %> 2 <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> 3 <style type="text/css"> 4 #divCut { 5 background-position: top left 6 } 7 </style> 8 <link href="/Css/imgareaselect-default.css" rel="stylesheet" /> 9 <script src="/js/jquery.imgareaselect.min.js"></script> 10 <script src="/SWFUpload/swfupload.js"></script> 11 <script src="/SWFUpload/handlers.js"></script> 12 <script type="text/javascript"> 13 var swfu; 14 window.onload = function () { 15 swfu = new SWFUpload({ 16 // Backend Settings 17 upload_url: "/ashx/upload.ashx?action=up", 18 post_params: { 19 "ASPSESSID": "<%=Session.SessionID %>" 20 }, 21 22 // File Upload Settings 23 file_size_limit: "2 MB", 24 file_types: "*.jpg;*.gif", 25 file_types_description: "JPG Images", 26 file_upload_limit: 0, // Zero means unlimited 27 28 // Event Handler Settings - these functions as defined in Handlers.js 29 // The handlers are not part of SWFUpload but are part of my website and control how 30 // my website reacts to the SWFUpload events. 31 swfupload_preload_handler: preLoad, 32 swfupload_load_failed_handler: loadFailed, 33 file_queue_error_handler: fileQueueError, 34 file_dialog_complete_handler: fileDialogComplete, 35 upload_progress_handler: uploadProgress, 36 upload_error_handler: uploadError, 37 upload_success_handler: showImage, 38 upload_complete_handler: uploadComplete, 39 40 // Button settings 41 button_image_url: "/SWFUpload/images/XPButtonNoText_160x22.png", 42 button_placeholder_id: "spanButtonPlaceholder", 43 button_width: 160, 44 button_height: 22, 45 button_text: '<span class="button">请选择上传图片<span class="buttonSmall">(2 MB Max)</span></span>', 46 button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }', 47 button_text_top_padding: 1, 48 button_text_left_padding: 5, 49 50 // Flash Settings 51 flash_url: "/SWFUpload/swfupload.swf", // Relative to this file 52 flash9_url: "/SWFUpload/swfupload_FP9.swf", // Relative to this file 53 54 custom_settings: { 55 upload_target: "divFileProgressContainer" 56 }, 57 58 // Debug Settings 59 debug: false 60 }); 61 } 62 //上传成功以后调用该方法 63 function showImage(file, serverData) { 64 //$("#imgSrc").attr("src", serverData); 65 var data = serverData.split(':'); 66 if (data[0] == "ok") { 67 //建上传成功的图片作为divContent的背景. 68 //$("#divContent").css("backgroundImage", "url(" + data[1] + ")").css("width", data[2] + "px").css("height", data[3] + "px"); 69 $("#selectbanner").attr("src", data[1]);//给定img的数据 70 $('#selectbanner').imgAreaSelect({ 71 selectionColor: 'blue', x1: 0, y1: 0, x2: 150, y2: 100, 72 73 //maxWidth: 950, minWidth: 950, minHeight: 400, maxHeight: 400, 74 75 selectionOpacity: 0.2, onSelectEnd: preview 76 }); 77 $('#selectbanner').data('x', 0); 78 79 $('#selectbanner').data('y', 0); 80 81 $('#selectbanner').data('w',150); 82 83 $('#selectbanner').data('h', 100); 84 $("#imagePath").val(data[1]);//将上传成功的头像存储到隐藏域中。 85 } else { 86 alert(serverData[1]); 87 } 88 } 89 //选择结束以后调用该方法(确定出要截取头像的范围,并且通过data方法存储要截取头像范围的数据) 90 function preview(img, selection) { 91 92 $('#selectbanner').data('x', selection.x1); 93 94 $('#selectbanner').data('y', selection.y1); 95 96 $('#selectbanner').data('w', selection.width); 97 98 $('#selectbanner').data('h', selection.height); 99 100 } 101 102 103 $(function () { 104 //$("#divCut").resizable({ 105 // containment: "parent" 106 //}).draggable({ containment: "parent" }); 107 $("#btnPhotoCut").click(function () { 108 ////确定要截取头像的范围。 109 //var y = $("#divCut").offset().top - $("#divContent").offset().top;//计算出纵坐标. 110 //var x = $("#divCut").offset().left - $("#divContent").offset().left; 111 //var width = $("#divCut").width(); 112 //var height = $("#divCut").height(); 113 //var pars = { 114 // x: x, 115 // y: y, 116 // width:width, 117 // height: height, 118 // action: "cut", 119 // imagePath: $("#imagePath").val() 120 121 //}; 122 123 var pars = { 124 125 x: $('#selectbanner').data('x'), 126 127 y: $('#selectbanner').data('y'), 128 129 width: $('#selectbanner').data('w'), 130 131 height: $('#selectbanner').data('h'), 132 133 imagePath: $("#imagePath").val(), 134 action: "cut", 135 136 }; 137 //根据确定的范围进行头像的截取. 138 $.post("/ashx/upload.ashx", pars, function (data) { 139 $("#imgSrc").attr("src", data);//截取成功后的数据 140 }); 141 }); 142 }); 143 </script> 144 145 146 </asp:Content> 147 <asp:Content ID="Content2" ContentPlaceHolderID="cphContent" runat="server"> 148 149 <div id="content"> 150 <div id="swfu_container" style="margin: 0px 10px;"> 151 <div> 152 <span id="spanButtonPlaceholder"></span> 153 </div> 154 <div id="divFileProgressContainer" style="height: 75px;"></div> 155 <div id="thumbnails"></div> 156 <%-- <div id="divContent" style="width:300px; height:300px"> 157 <div id="divCut" style="width:100px; height:100px;border:solid 1px red"> 158 159 </div> 160 </div>--%> 161 <img id="selectbanner"/> 162 <input type="button" value="头像截取" id="btnPhotoCut" /> 163 <input type="hidden" id="imagePath" /> 164 <br /> 165 <img id="imgSrc" /> 166 </div> 167 </div> 168 </asp:Content>
1 using System; 2 using System.Collections.Generic; 3 using System.Drawing; 4 using System.IO; 5 using System.Linq; 6 using System.Web; 7 8 namespace Maticsoft.Web.ashx 9 { 10 /// <summary> 11 /// upload 的摘要说明 12 /// </summary> 13 public class upload : IHttpHandler 14 { 15 16 public void ProcessRequest(HttpContext context) 17 { 18 context.Response.ContentType = "text/plain"; 19 //context.Response.Write("Hello World"); 20 string action = context.Request["action"]; 21 if (action == "up") 22 { 23 fileUpload(context);//上传图片 24 25 } 26 else if (action == "cut") 27 { 28 cutFileImage(context);//截取图片文件 29 } 30 else 31 { 32 context.Response.Write("参数异常!1"); 33 } 34 } 35 #region 截取图片文件 36 37 private void cutFileImage(HttpContext context) 38 { 39 int x = Convert.ToInt32(context.Request["x"]); 40 int y = Convert.ToInt32(context.Request["y"]); 41 int width = Convert.ToInt32(context.Request["width"]); 42 int height = Convert.ToInt32(context.Request["height"]); 43 string imagePath = context.Request["imagePath"]; 44 using (Bitmap map = new Bitmap(width,height)) 45 { 46 using (Graphics g = Graphics.FromImage(map)) 47 { 48 using (Image img = Image.FromFile(context.Request.MapPath(imagePath))) 49 { 50 //将原图的指定范围画到画布上. 51 //1:表示对哪张图片进行操作 52 //2:画多么大. 53 //3:画原图的哪块区域 54 g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel); 55 string fileNewName = Guid.NewGuid().ToString(); 56 string fullDir = "/UploadImage/" + fileNewName + ".jpg"; 57 map.Save(context.Request.MapPath(fullDir), System.Drawing.Imaging.ImageFormat.Jpeg);//保存图片. 58 //一定要将截取后的图片路径存储到数据库中。 59 context.Response.Write(fullDir); 60 } 61 } 62 } 63 //throw new NotImplementedException(); 64 } 65 #endregion 66 #region 上传图片 67 private void fileUpload(HttpContext context) 68 { 69 HttpFileCollection collection = context.Request.Files; 70 bool isSucess = false; 71 if (collection.Count > 0) 72 { 73 HttpPostedFile file = context.Request.Files["Filedata"]; 74 if (file != null) 75 { 76 string fileName = Path.GetFileName(file.FileName); 77 string fileExt = Path.GetExtension(fileName); 78 if (fileExt == ".jpg") 79 { 80 string dir = "/UploadImage/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/"; 81 if (!Directory.Exists(context.Request.MapPath(dir))) 82 { 83 Directory.CreateDirectory(context.Request.MapPath(dir)); 84 } 85 string newfileName = Guid.NewGuid().ToString(); 86 string fullDir = dir + newfileName + fileExt; 87 file.SaveAs(context.Request.MapPath(fullDir)); 88 isSucess = true; 89 using (Image img = Image.FromFile(context.Request.MapPath(fullDir))) 90 { 91 context.Response.Write("ok:" + fullDir + ":" + img.Width + ":" + img.Height); 92 } 93 //file.SaveAs(context.Request.MapPath("/UploadImage/" + fileName)); 94 //context.Response.Write("/UploadImage/" + fileName); 95 } 96 } 97 } 98 if (!isSucess) 99 { 100 context.Response.Write("no:上传失败!!"); 101 } 102 } 103 #endregion 104 105 public bool IsReusable 106 { 107 get 108 { 109 return false; 110 } 111 } 112 } 113 }
2 基本登陆与自动登录
3 返回上次访问位置
1 using Maticsoft.BLL; 2 using System; 3 using System.Collections.Generic; 4 using System.Linq; 5 using System.Web; 6 7 namespace Maticsoft.Web.CheckUserState 8 {//使用频率较高时 其他页面直接继承checkusersession 就不需要多次书写 9 public class CheckSession : System.Web.UI.Page 10 { 11 public void Page_Init(object sender, EventArgs e) 12 { 13 if (Session["userInfo"] == null) 14 { 15 if (Request.Cookies["cp1"] != null) 16 { 17 UsersManager userManager = new UsersManager(); 18 string userName = Request.Cookies["cp1"].Value;//查询是否存在此用户名 19 Model.Users userInfo = userManager.GetModel(userName); 20 if (!Common.WebCommon.CheckCookieInfo(userInfo)) 21 { 22 // Response.Redirect("/Account/Login.aspx"); 23 Common.WebCommon.ReturnRedirect(); 24 } 25 } 26 else 27 { 28 //Response.Redirect("/Account/Login.aspx"); 29 Common.WebCommon.ReturnRedirect(); 30 } 31 } 32 } 33 } 34 }
4 退出登录
/// <summary> /// 清除session /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); if (context.Session["userInfo"] != null) { context.Session["userInfo"] = null; //清除cookie中的值 context.Response.Cookies["cp1"].Expires = DateTime.Now.AddDays(-1); context.Response.Cookies["cp2"].Expires = DateTime.Now.AddDays(-1); context.Response.Write("ok"); } }
5 注册跳转
验证码每次点击登录时直接强制过期,应该是为了,减少服务器端压力
6 找回密码
采用的是数据库更新密码,邮件发送新密码,数据库更新一定放在发送邮件后,防止邮件未发送而密码更改,
/// <summary> /// 发送邮件 /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); string mail = context.Request["mail"]; UsersManager userInfoManager = new UsersManager(); if (userInfoManager.CheckUserMail(mail))//表示有这个邮箱 { userInfoManager.SendUserMail(mail); context.Response.Write("ok"); } else { context.Response.Write("no"); } }
public bool CheckUserMail(string mail) { return dal.CheckUserMail(mail) > 0; }
/// <summary> /// 发送邮件 利用数据库存储源邮件信息,并存储在缓存中 /// </summary> /// <param name="mail"></param> public void SendUserMail(string mail) { //1:系统产生一个新的密码(一定要替换用户在数据库中的旧密码,但是发送到用户邮箱中的密码必须是明文),发送到用户邮箱中。 //2:发送一个连接. SettingsManager settingManager = new SettingsManager(); string newPwd = Guid.NewGuid().ToString().Substring(0, 8); Model.Users userInfo = dal.GetUserByMail(mail);//根据邮箱找用户 userInfo.LoginPwd = Common.WebCommon.Md5String(Common.WebCommon.Md5String(newPwd)); //注释的是用来邮件发送的缓存用法 MailMessage mailMsg = new MailMessage();//两个类,别混了,要引入System.Net这个Assembly mailMsg.From = new MailAddress(settingManager.GetModel("系统邮件地址").Value);//源邮件地址 mailMsg.To.Add(new MailAddress(mail));//目的邮件地址。可以有多个收件人 mailMsg.Subject = "您在xxx网站新的账户";//发送邮件的标题 StringBuilder sb = new StringBuilder(); sb.Append("您在xxx网站中新的账户如下:"); sb.Append("用户名:"+userInfo.LoginId); sb.Append("密码是:"+newPwd); mailMsg.Body = sb.ToString();//发送邮件的内容 mailMsg.IsBodyHtml = true; //指定Smtp服务地址。(根据发件人邮箱指定对应的SMTP服务器地址) //SmtpClient client = new SmtpClient("smtp.qq.com"); SmtpClient client = new SmtpClient(settingManager.GetModel("系统邮件SMTP").Value);//smtp.163.com,smtp.qq.com client.Credentials = new NetworkCredential(settingManager.GetModel("系统邮件用户名").Value, settingManager.GetModel("系统邮件密码").Value);//发件人邮箱的用户名密码 client.Send(mailMsg); dal.Update(userInfo);//这一项必须放在最后 }
/// <summary> /// 根据配置项的名称找对应配置信息 /// </summary> /// <param name="name">配置项的名称(key)</param> /// <returns></returns> public Model.Settings GetModel(string name) { object obj = Common.CacheHelper.Get("setting_" + name); if (obj == null) { Model.Settings setting = dal.GetModel(name); Common.CacheHelper.Set("setting_" + name, setting); return setting; } else { Model.Settings setting = obj as Model.Settings; return setting; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace Maticsoft.Common { public class CacheHelper { /// <summary> /// 根据缓存的key,从缓存中取值. /// </summary> /// <param name="key"></param> /// <returns></returns> public static object Get(string key) { System.Web.Caching.Cache cache = HttpRuntime.Cache; return cache[key]; } /// <summary> /// 向缓存中添加数据 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public static void Set(string key, object value) { System.Web.Caching.Cache cache = HttpRuntime.Cache; cache[key] = value; } /// <summary> /// 向缓存中添加数据 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public static void Set(string key, object value,DateTime time) { System.Web.Caching.Cache cache = HttpRuntime.Cache; cache.Insert(key, value, null, time, TimeSpan.Zero); } /// <summary> /// 移除缓存中的数据 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public static void Reomve(string key) { System.Web.Caching.Cache cache = HttpRuntime.Cache; cache.Remove(key); } } }