前篇:
个人中心页面需要用户自己修改自己的头像,在这里我使用的是base64编码来进行图片的显示,使用的是WEB三层架构带接口架构
页面搭建
需要有一个修改图片的页面让用户进行选择自己需要修改的图片和个人中心页面
样式: <style> .avataredit .uploadselect { border: 1px solid; width: 100px; height: 100px; color: #ccc; transition: color .25s; position: relative; } .avataredit .uploadselect::before { content: ''; position: absolute; left: 50%; top: 50%; width: 80px; margin-left: -40px; margin-top: -5px; border-top: 10px solid; } .avataredit .uploadselect::after { content: ''; position: absolute; left: 50%; top: 50%; height: 80px; margin-left: -5px; margin-top: -40px; border-left: 10px solid; } .avataredit .upload { width: 100px; height: 100px; display: block; border: none; opacity: 0; } </style> 页面内容: <div class="page" data-page="avataredit"> <div class="page-content"> <div class="block-title">编辑头像</div> <div class="list inline-labels no-hairlines-md"> <ul> <li> <div class="item-content item-input"> <div class="item-inner"> <div class="item-title item-label">上传头像</div> <div class="item-input-wrap padding-top padding-bottom"> <div id="uploadselect" class="uploadselect"> <input type="file" id="upload" class="upload" accept="image/*" /> </div> <asp:HiddenField ID="hfAvatar" runat="server" /> </div> </div> </div> </li> </ul> </div> <div class="block block-strong"> <asp:ValidationSummary ID="vsLogin" runat="server" ShowMessageBox="True" ShowSummary="False" /> <asp:Button ID="btnAvatar" runat="server" Text="立即更新" CssClass="button button-fill button-large button-round" OnClick="btnAvatar_Click" /> </div> </div> </div>搭建修改头像页面
样式: <style> .personal .avatar { width: 6em; height: 6em; overflow: hidden; position: relative; } .personal .avatar img { width: 100%; height: 100%; border-radius: 50%; } .personal .avatar .edit { width: 22px; height: 22px; display: inline-block; padding: 4px; background: rgba(255,255,255,0.5); border-radius: 50%; position: absolute; z-index: 999; top: 0; right: 0; } .personal .nickname { display: inline-block; line-height: 1.6em; } .personal .sex { display: inline-block; width: 5em; font-size: 0.8em; line-height: 1.6em; border-radius: 0.8em; text-align: center; color: #ffffff; } </style> 内容:<div class="page" data-page="personal"> <div class="page-content"> <div class="block block-strong personal margin-top-none"> <div class="row"> <div class="col-30"> <div class="avatar float-right"> <a class="edit external edit" href="AvatarEdit.aspx"><i class="f7-icons text-color-gray size-22">camera_viewfinder</i></a> <asp:Image ID="imgAvatar" runat="server" /> </div> </div> <div class="col-70"> <div class="row"> <div class="col-100 margin-top-quarter margin-bottom-half"> <a href="PersonalEdit.aspx" class="external"><i class="f7-icons float-right size-22 text-color-gray">gear</i></a> <asp:Label ID="lblNickName" runat="server" Text="" CssClass="nickname"></asp:Label> <asp:Label ID="lblSex" runat="server" Text="" CssClass="sex margin-left"></asp:Label> </div> <div class="col-60"> <p class="margin-top-quarter margin-bottom-quarter"><i class="f7-icons size-14 text-color-gray margin-right-half">placemark</i><asp:Label ID="lblAddress" runat="server" Text=""></asp:Label></p> </div> <div class="col-40"> <p class="margin-top-quarter margin-bottom-quarter"><i class="f7-icons size-14 text-color-gray margin-right-half">gift</i><asp:Label ID="lblBirthday" runat="server" Text=""></asp:Label></p> </div> <div class="col-100"> <p class="margin-top-quarter margin-bottom-quarter"><i class="f7-icons size-14 text-color-gray margin-right-half">heart</i><asp:Label ID="lblHobby" runat="server" Text=""></asp:Label></p> </div> </div> </div> </div> </div> <div class="list"> <ul> <li> <a href="Friends.aspx" class="item-link item-content external"> <div class="item-media"><i class="f7-icons">person_2</i></div> <div class="item-inner"> <div class="item-title">我的好友</div> </div> </a> </li> </ul> </div> <div class="list"> <ul> <li> <a href="MyVideos.aspx" class="item-link item-content external"> <div class="item-media"><i class="f7-icons">play_rectangle</i></div> <div class="item-inner"> <div class="item-title">我的视频</div> </div> </a> </li> <li> <a href="Publish.aspx" class="item-link item-content external"> <div class="item-media"><i class="f7-icons">camera</i></div> <div class="item-inner"> <div class="item-title">发布视频</div> </div> </a> </li> </ul> </div> </div> </div> <div class="toolbar tabbar tabbar-labels toolbar-bottom"> <div class="toolbar-inner"> <a href="Default.aspx" class="tab-link external"> <i class="icon f7-icons size-29">videocam</i> <span class="tabbar-label">视频</span> </a> <a href="Friends.aspx" class="tab-link external"> <i class="icon f7-icons size-22">bubble_left_bubble_right</i> <span class="tabbar-label">聊天</span> </a> <a href="Personal.aspx" class="tab-link external tab-link-active"> <i class="icon f7-icons size-25">person</i> <span class="tabbar-label">我的</span> </a> </div> </div>搭建个人中心页面
页面展示:
插入对应的jQuery代码:
<script src="lib/lrz/dist/lrz.bundle.js"></script> <script> document.querySelector('#upload').addEventListener('change', function () { lrz(this.files[0], { width: 300, height: 300 }) .then(function (rst) { // 上传文件数据 var xhr = new XMLHttpRequest(); xhr.open('POST', 'ASPh/ImageUpload.ashx?length=' + rst.base64Len); xhr.onload = function () { if (xhr.status === 200) { document.getElementById('BodyContent_hfAvatar').value = xhr.responseText; } else { alert('图片上传失败!'); } }; xhr.send(rst.base64); // 在页面中显示图片 var img = new Image(); img.src = rst.base64; img.width = 100; img.height = 100; document.getElementById('uploadselect').parentNode.appendChild(img); document.getElementById('uploadselect').remove(); // 返回对象 return rst; }) .catch(function (err) { console.log(err); alert('图片上传失败!'); }); }); </script>jQuery代码
注意:在该jQuery中应与存放的ImageUpload路径写对,不然会一直报错。
在业务逻辑层(BLL)引入身份标识业务管理类(IdentityManager)
/// <summary> /// 身份标识业务管理类 /// </summary> public class IdentityManager { /// <summary> /// 保存用户信息 /// </summary> /// <param name="user"></param> public static void SaveUser(TBUsers user) { if (user == null) { return; } // 序列化用户资料 string profileString = JsonConvert.SerializeObject(user); // 生成身份票据 DateTime timeNow = DateTime.Now; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, user.Id.ToString(), timeNow, timeNow.AddMonths(1), false, profileString, FormsAuthentication.FormsCookiePath); string ticketString = FormsAuthentication.Encrypt(ticket); // 保存身份票据到Cookie HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketString); cookie.Expires = timeNow.AddMonths(1); HttpContext.Current.Response.Cookies.Set(cookie); } /// <summary> /// 读取用户信息 /// </summary> /// <returns></returns> public static TBUsers ReadUser() { // 读取身份 string ticketString = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]?.Value; if(string.IsNullOrWhiteSpace(ticketString)) { return default; } FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(ticketString); string userData = ticket.UserData; // 反序列化用户资料 TBUsers user = JsonConvert.DeserializeObject<TBUsers>(userData); return user; } }身份标识业务管理类
然后在该页面的web窗体下新建个一般处理程序(ImageUpload)
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Web; namespace HIPI.AiXiu.ASPh { /// <summary> /// ImageUpload 的摘要说明 /// </summary> public class ImageUpload : IHttpHandler { public void ProcessRequest(HttpContext context) { //1、读取URL传递的length,若小于等于0则返回400-错误请求,结束响应,返回 //2、读取编码流长度,若小于等于0则返回400,结束响应,返回 //3、获取二进制(封装调用) //3.1、创建byte[]类并设置长度为当前编码流长度(context.Request.InputStream.Length) //3.2、调用InputStream.Read方法从当前流中读取编码流长度赋值给byte[]中 //3.3、将当前byte[]类型中的字节编码为一个字符串(Encoding.Default.GetString) //4、图片命名-Guid.NewGuid().ToString("N") //5、设置图片物理路径拼接图片名称 //6、设置相对路径 //7、定义并实例化一个内存流,以存放图片的字节数组MemoryStream //8、使用指定的数据流中嵌入Image,从该数据流创建(Image.FromStream) //8、输出相对路径 var length = context.Request.QueryString["length"]; if (string.IsNullOrWhiteSpace(length) || int.Parse(length) <= 0) { context.Response.StatusCode = 400; context.Response.End(); } if (context.Request.InputStream == null || context.Request.InputStream.Length <= 0) { context.Response.StatusCode = 400; context.Response.End(); } byte[] bytes = baseByte(context); string imgName= Guid.NewGuid().ToString("N"); string imgUrl = context.Server.MapPath($"~/Avatar/{imgName}"+".jpg"); string imgSrc = "/Avatar/" + imgName + ".jpg"; using (MemoryStream stream=new MemoryStream(bytes)) { Image image = Image.FromStream(stream); image.Save(imgUrl, ImageFormat.Jpeg); } context.Response.StatusCode = 200; context.Response.Write(imgSrc); context.Response.End(); } public byte[] baseByte(HttpContext context) { //3、创建byte[]类并设置长度为当前编码流长度 //4、调用InputStream.Read方法从当前流中读取编码流长度赋值给byte[]中 //5、将当前byte[]类型中的字节编码为一个字符串(Encoding.Default.GetString) byte[] base64Bytes = new byte[context.Request.InputStream.Length]; context.Request.InputStream.Seek(0, SeekOrigin.Begin); context.Request.InputStream.Read(base64Bytes, 0, base64Bytes.Length); string base64String = Encoding.Default.GetString(base64Bytes); base64String = base64String.Substring(base64String.IndexOf("base64") + 7); byte[] baseByte = Convert.FromBase64String(base64String); return baseByte; } public bool IsReusable { get { return false; } } } }ImageUpload一般处理程序
注意:此处应新建个存放图片的文件夹Avatar。
添加Model类库并添加一个带返回值的返回结果类 OperResult<T>(此处运用泛型)
/// <summary> /// 带返回值的返回结果类 /// </summary> public class OperResult<T> { /// <summary> /// 状态码 /// </summary> public StatusCode StatusCode { get; protected set; } public T Data { get; protected set; } /// <summary> /// 结果对象 /// </summary> public T Result { get; protected set; } /// <summary> /// 消息 /// </summary> public string Message { get; protected set; } /// <summary> /// 异常 /// </summary> public Exception Exception { get; protected set; } /// <summary> /// 读取结果 /// </summary> /// <returns></returns> public T ReadResult() { if (Result is T) { return (T)Result; } else { return default(T); } } /// <summary> /// 操作成功 /// </summary> /// <param name="result"></param> /// <returns></returns> public static OperResult<T> Succeed(T result) { return new OperResult<T>() { StatusCode = StatusCode.Succeed, Result = result, Message = "操作成功!" }; } /// <summary> /// 操作失败 /// </summary> /// <param name="message"></param> /// <returns></returns> public static OperResult<T> Failed(string message = null) { return new OperResult<T>() { StatusCode = StatusCode.Failed, Message = message ?? "操作失败!" }; } /// <summary> /// 操作异常 /// </summary> /// <param name="exception"></param> /// <param name="message"></param> /// <returns></returns> public static OperResult<T> Wrong(Exception exception, string message = null) { return new OperResult<T>() { StatusCode = StatusCode.Wrong, Message = message ?? exception.Message, Exception = exception }; } } /// <summary> /// 返回结果状态码 /// </summary> public enum StatusCode { Succeed, Failed, Wrong }带返回值的返回结果类 OperResult
最后在三层中查找数据库中图片并更新:
在IBLL层写入:
//更新用户头像 OperResult<TBUsers> Edit(TBUsers user);更新用户头像
在BLL层写入:
/// <summary> /// 更新用户头像 /// </summary> /// <param name="user"></param> /// <returns></returns> public OperResult<TBUsers> Edit(TBUsers user) { IUserService userService = new UserService(); try { TBUsers profileEntity = userService.fintouxiang(user); return OperResult<TBUsers>.Succeed(profileEntity); } catch (Exception ex) { return OperResult<TBUsers>.Failed(ex.ToString()); } }更新用户头像
在IDAL层写入:
//根据id更新头像 TBUsers fintouxiang(TBUsers profile);根据id更新头像
在DAL层写入:
public TBUsers fintouxiang(TBUsers profile) { IShowDbContext DB = new IShowDbContext(); TBUsers tb = DB.TBUsers.FirstOrDefault(a => a.Id == profile.Id); if (tb==null) { return null; } tb.Avatar = profile.Avatar; //更新到数据库 DB.SaveChanges(); return tb; }根据id修改头像
最后激发修改界面的修改按钮事件(修改成功并跳转个人中心页面):
TBUsers tBUsers = IdentityManager.ReadUser(); tBUsers.Avatar = this.hfAvatar.Value; if (string.IsNullOrWhiteSpace(this.hfAvatar.Value)) { this.Alert("img","请先上传图片"); return; } //更新资料 IAccountManager profileManager = new AccountManager(); OperResult<TBUsers> EditResult = profileManager.Edit(tBUsers); if (EditResult.StatusCode==StatusCode.Succeed) { //更新缓存用户资料 IdentityManager.SaveUser(EditResult.Result); //跳转到个人页 Response.Redirect("Personal.aspx"); } else { this.Alert("editerror",EditResult.Message); }单机事件代码
效果图:
标签:web,return,OperResult,头像,TBUsers,上传,public,StatusCode From: https://www.cnblogs.com/dabaibai22/p/16757850.html