ASP.Net多用户头像修改

版权声明:转载原创文章请以超链接形式请注明原文章出处,尊重作者,尊重原创!


恰饭广告




实现效果:

实现效果

注意:

1.每注册一个用户将新建一个用户文件夹,用于存储用户的图片

2.只能上传jpg jpeg png格式的图片,不包括1.txt.jpg类似文件

3.新用户默认有系统头像,修改新头像将会删除掉旧头像

4.session设置为一分钟

数据库表:

数据库表内容

项目的数据模块图:

项目结构图

BLL层:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebApplication5.DAL;
using WebApplication5.Model;
namespace WebApplication5.BLL
{
    public class UserInfoBLL
    {
        UserInfoDAL userInfoDal = new UserInfoDAL();
        #region 判断用户名是否存在
        public int UserName(UserInfo user)
        {
            int count = userInfoDal.UserName(user);
            return count;
        }
        #endregion
        #region 用户注册
        public bool Insert(UserInfo user)
        {
            int count = userInfoDal.UserName(user);
            if (count > 0)
            {
                return false;
            }
            else
            {
                user.url = @"\Imgs\system\system.jpg";
                userInfoDal.Insert(user);
                return true;
            }
        }
        #endregion
        #region 用户登录
        public UserInfo SelectUser(string userName, string password)
        {
            return userInfoDal.SelectUser(userName, password);
        }
        #endregion
        #region 更新图片
        public void updateImg(UserInfo user)
        {
            userInfoDal.updateImg(user);
        }
        #endregion
        #region 获取路径,删除图片
        public UserInfo delImg(string userName)
        {
            return userInfoDal.delImg(userName);
        }
        #endregion
    }
}

DAL层:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using WebApplication5.Model;
namespace WebApplication5.DAL
{
    public class UserInfoDAL
    {
        SQLHelper sqlHelp = new SQLHelper();
        #region 判断用户名是否存在
        public int UserName(UserInfo user)
        {
            int i = Convert.ToInt32(sqlHelp.ExecuteScalar("select count(*) from T_UserImg where userName=@userName",
                 new SqlParameter("@userName", user.userName)));
            return i;
        }
        #endregion
        #region 用户注册
        public void Insert(UserInfo user)
        {
            sqlHelp.ExecuteNonQuery(@"INSERT INTO T_UserImg
                       (userName,password,picUrl)
                        VALUES
                       (@UserName,@password,@url)",
                new SqlParameter("@userName", user.userName),
                new SqlParameter("@password", user.password),
                new SqlParameter("@url", user.url));
        }
        #endregion
        #region 用户登录
        public UserInfo SelectUser(string userName, string password)
        {
            UserInfo user = new UserInfo();
            SqlDataReader reader = sqlHelp.ExecuteSqlReader("select * from T_UserImg where userName=@userName and password=@password",
                new SqlParameter("@userName", userName),
                new SqlParameter("@password", password));
            while (reader.Read())
            {
                user.userName = reader.GetString(0);
                user.password = reader.GetString(1);
                user.url = reader.GetString(2);
            }
            reader.Close();
            return user;
        }
        #endregion
        #region 更新图片
        public void updateImg(UserInfo user)
        {
            sqlHelp.ExecuteNonQuery(@"update T_UserImg set picUrl=@url where userName=@userName",
                new SqlParameter("@userName", user.userName),
                new SqlParameter("@url", user.url));
        }
        #endregion
        #region 获取图片路径,删除图片
        public UserInfo delImg(string userName)
        {
            UserInfo user = new UserInfo();
            SqlDataReader reader = sqlHelp.ExecuteSqlReader("select * from T_UserImg where userName=@userName",
                new SqlParameter("@userName", userName));
            while (reader.Read())
            {
                user.userName = reader.GetString(0);
                user.url = reader.GetString(2);
            }
            reader.Close();
            return user;
        }
        #endregion
    }
}

Model层(Entity类):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication5.Model
{
    public class UserInfo
    {
        public UserInfo() { }
        public string userName { get; set; }
        public string password { get; set; }
        public string url { get; set; }
    }
}

UI层:

WebForm1.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication5.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="Label1" runat="server" Text="姓名:"></asp:Label>
            <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
        </div>
        <asp:Label ID="Label2" runat="server" Text="密码:"></asp:Label>
        <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        <br />
        <asp:Button ID="btnReg" runat="server" Text="注册" OnClick="btnReg_Click" />
        <asp:Button ID="btnLogin" runat="server" Text="登录" OnClick="btnLogin_Click" style="width: 40px" />
    </form>
</body>
</html>

WebForm1.aspx.cs代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplication5.BLL;
using WebApplication5.Model;
namespace WebApplication5
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        UserInfo user = new UserInfo();
        UserInfoBLL userBll = new UserInfoBLL();
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void btnReg_Click(object sender, EventArgs e)
        {
            user.userName = txtUserName.Text.Trim();
            user.password = txtPassword.Text.Trim();
            if (user.userName == "")
            {
                Response.Write("请输入用户名!");
                return;
            }
            if (user.password == "")
            {
                Response.Write("请输入密码!");
                return;
            }
            int count = userBll.UserName(user);
            if (count > 0)
            {
                Response.Write("用户名已存在");
                return;
            }
            if (userBll.Insert(user))
            {
                Response.Write("注册成功");
                Directory.CreateDirectory(Server.MapPath("/Imgs/user/"+user.userName));
            }
            else
            {
                Response.Write("注册失败!");
            }
        }
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string userName = txtUserName.Text.Trim();
            string password = txtPassword.Text.Trim();
            if (userName == "")
            {
                Response.Write("请输入用户名!");
                return;
            }
            if (userName == "")
            {
                Response.Write("请输入密码!");
                return;
            }
            UserInfo user = userBll.SelectUser(userName, password);
            if (userName == user.userName)
            {
                //Response.Write("登录成功");
                Session["picUrl"] = user.url;
                Session["userName"] = user.userName;
                Session.Timeout = 1;
                Response.Redirect("WebForm2.aspx");
            }
            else
            {
                Response.Write("用户名密码错误");
            }
        }
    }
}

WebForm2.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication5.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script>
        function showImg(file) {
            var prevDiv = document.getElementById("Image1");
            var aa = document.getElementById("upUserPic").value.toLowerCase().split('.');
            if (aa[aa.length - 1] == 'png' || aa[aa.length - 1] == 'jpg' || aa[aa.length - 1] == 'jpeg') {
                if (file.files && file.files[0]) {
                    var reader = new FileReader();
                    reader.onload = function (evt) {
                        prevDiv.src = evt.target.result;
                    }
                    reader.readAsDataURL(file.files[0]);
                }
                return true;
            }
            else {
                alert('对不起,你选择的图片格式不对\n图片格式应为*.jpg、*.png、*.jpeg');
                document.getElementById('upUserPic').value = "";
                prevDiv.src = "";
                return false;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Image ID="Image1" runat="server" Width="50px" /><br />
        <asp:FileUpload ID="upUserPic" runat="server" onchange="showImg(this)" /><br />
        <asp:Label ID="labConfirm" runat="server"></asp:Label>
        <p>
            <asp:Button ID="btnChange" runat="server" Text="确认修改" OnClick="btnChange_Click" />
            <asp:Button ID="btnExit" runat="server" OnClick="btnExit_Click" Text="退出登录" />
        </p>
    </form>
</body>
</html>

WebForm2.aspx.cs代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplication5.BLL;
using WebApplication5.Model;
namespace WebApplication5
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        UserInfo user = new UserInfo();
        UserInfoBLL userBll = new UserInfoBLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["userName"] == null)
            {
                Response.Redirect("WebForm1.aspx");
            }
            else
            {
                Response.Write("登录用户:"+Session["userName"].ToString());
                Image1.ImageUrl = Session["picUrl"].ToString();
            }
        }
        protected void btnChange_Click(object sender, EventArgs e)
        {
            string path = "/Imgs/user/"+ Session["userName"].ToString()+"/";
            bool filesValid = false;
            //DateTime now = DateTime.Now;
            string fileName = Path.GetFileNameWithoutExtension(upUserPic.FileName);
            //string fileName = "" + now.Year + now.Month + now.Day + now.Hour + now.Minute + now.Second + now.Millisecond;
            if (upUserPic.HasFile)
            {
                String fileExtension = Path.GetExtension(upUserPic.FileName).ToLower();
                String[] restrictExtension = { ".jpg", ".jpeg", ".png" };
                for (int i = 0; i < restrictExtension.Length; i++)
                {
                    double mb = upUserPic.PostedFile.ContentLength / 1024 / 1024.0;
                    if (fileExtension == restrictExtension[i] && mb <= 4)
                    {
                        filesValid = true;
                    }
                }
                if (filesValid == true)
                {
                    try
                    {
                        Image1.ImageUrl = Session["picUrl"].ToString();
                        upUserPic.SaveAs(Server.MapPath(path) + fileName + fileExtension);
                        user = userBll.delImg(Session["userName"].ToString());
                        if (user.url != @"\Imgs\system\system.jpg")
                        {
                            File.Delete(Server.MapPath(user.url));
                        }
                        string imgPath = path + Path.GetFileName(upUserPic.PostedFile.FileName);
                        user.userName = Session["userName"].ToString();
                        user.url = imgPath;
                        userBll.updateImg(user);
                        Image1.ImageUrl = imgPath;
                        labConfirm.Text = "修改成功";
                    }
                    catch
                    {
                        labConfirm.Text = "上传失败";
                    }
                    finally
                    {
                        Image1.Dispose();
                    }
                }
                else
                {
                    labConfirm.Text = "修改失败";
                }
            }
            else
            {
                labConfirm.Text = "格式错误";
                Image1.ImageUrl = Session["picUrl"].ToString();
            }
        }
        protected void btnExit_Click(object sender, EventArgs e)
        {
            Session.Remove("userName");
            Session.Abandon();
            Response.Redirect("WebForm1.aspx");
        }
    }
}

还有数据库访问类(SQLHelper.cs)代码太多就不贴出来了

GitHub源码下载:https://github.com/kiritobin/ChangeHeadImg3Fram

原文链接:https://www.idaobin.com/archives/1252.html

让我恰个饭吧.ヘ( ̄ω ̄ヘ)

支付宝 ——————- 微信
图片加载中图片加载中



恰饭广告

发表评论

电子邮件地址不会被公开。 必填项已用*标注

÷ 1 = 5