利用一般处理程序处理头像的浏览和更新

来源:互联网 发布:关于广州plc编程员招聘 编辑:程序博客网 时间:2024/06/05 06:08

环境: Vs2012 SQLServer

思路:SQLServer来处理图片文件名,更新和浏览都是通过更换文件名

 

头像显示


    HTML

   

<div id="localImag" style="width: 328px; float: left; height: 113px;">                            <img id="preview" src="SearchCompanyPhoto.ashx" width="140" height="150" />                        </div>
   

    这里如以往不尽相同的是,src里面书写的是一般处理程序的名称。


   一般处理程序

  

  

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Text;using BLL;using System.Web.SessionState;//引入读写操作using System.IO;namespace GoodCommunitySystem{    /// <summary>    /// SearchCompanyPhoto 的摘要说明    /// </summary>    public class SearchCompanyPhoto : IHttpHandler, IReadOnlySessionState     {        public void ProcessRequest(HttpContext context)        {            //当session有值的时候才能够上传头像            if (context.Session["UserName"] != null){                companyBLL companybll = new companyBLL();                Entity.companyEntity encompanyInfo = new Entity.companyEntity();                           StringBuilder strWhere = new StringBuilder();                //拿到session中存在的用户id值                string userID = context.Session["UserID"].ToString();                 string userName=context.Session["UserName"].ToString();                encompanyInfo = companybll.GetEntity(userID);                //获取头像地址                string HeadImg = encompanyInfo.HeadImg;                //把头像地址转换为绝地地址                string img = context.Server.MapPath(HeadImg);                // 以二进制方式读文件                  FileStream aFile = new FileStream(img, FileMode.OpenOrCreate, FileAccess.ReadWrite);                // 创建一个二进制数据流读入器,和打开的文件关联                  BinaryReader brMyfile = new BinaryReader(aFile);                // 把文件指针重新定位到文件的开始                  brMyfile.BaseStream.Seek(0, SeekOrigin.Begin);                //获取照片的字节数组                  byte[] photo = brMyfile.ReadBytes(Convert.ToInt32(aFile.Length.ToString()));                // 关闭以上new的各个对象                  brMyfile.Close();                context.Response.BinaryWrite(photo);            }            else            {                return;            }        }        public bool IsReusable        {            get            {                return false;            }        }    }}

   这里需要注意的就是引入了文件的IO操作,还就是在类后面继承这个类IReadOnlySessionState。用来处理session对象。还有一个就是二进制流文件的处理,这里采用的是将文件名转换为二进制文件。这样才能后显示在界面上,有些诡异。但是仔细一想,如果这个是在unix上浏览的网页。而unix定义变量的大小都不一样,肯定是无法读取到这个你再windows定义的文件名的。所以二进制就能够很好的解决问题。


头像浏览和上传

 

    HTML


   

<asp:FileUpload ID="FileUpload1" runat="server" onchange="javascript:setImagePreview(this,localImag,preview);" style="width: 245px; margin-left: -125px; "/><input id="Button1" type="button" onclick="SavePhoto()" value="确认上传头像" style="margin-left: 200px;"/>

     JS

   

        function SavePhoto() {            document.getElementById("test").value = "SavePhoto";//设定表示为后台调不同方法数据            var form = document.forms["TabData"];            form.action = "EditCompanyInfo.aspx";            form.method = "POST";            form.submit();        }

   后端代码

   

using BLL;using Entity;using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace GoodCommunitySystem{    public partial class EditCompanyInfomation : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            var test = Request.Form["test"];            //当session中不存在值,页面重定向到首页            if (Session["UserName"] == null)            {                Response.Redirect("default.aspx");            }            else            {                                if (test == "SavePhoto")                {                        //上传头像                        UpdatePhoto();                }                            }        }        companyBLL companybll = new companyBLL();        companyEntity encompany = new companyEntity();        public void UpdatePhoto()        {            if (Session["UserName"] == null)            {                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('您尚未登录,请登录!');</script>");                //Response.Write("<script language='javascript'>alert('请重新登录!');</script>");                return;            }            if (this.FileUpload1.FileContent.Length <= 0)            {                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('请您重新上传头像,谢谢!');</script>");                return;            }            if (this.FileUpload1.FileContent.Length >= 200000)            {                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('照片不能超过200KB!');</script>");                return;            }            String fullfilename = this.FileUpload1.PostedFile.FileName;    //获取图片的绝对路径            String filename = fullfilename.Substring(fullfilename.LastIndexOf("\\") + 1);//获取图片的名称            String type = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();            //获取图片的格式(类型)            String Rename = Session["UserName"] + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");     //用户名+时间命名,避免上传图片命名重复            string varToDirectory = Request.PhysicalApplicationPath + "touxiang";  //专门存放用户相册的文件            //判断文件是否存在,不存在则创建该文件            if (!Directory.Exists(varToDirectory))            {                Directory.CreateDirectory(varToDirectory);            }            if (type == "jpg" || type == "png" || type == "jpeg" || type == "gif")            {                companyEntity enCompanyInfo = new companyEntity();                enCompanyInfo.UserID = Session["UserID"].ToString();                enCompanyInfo.HeadImg = "touxiang/" + Rename + "." + type;  //数据库中中图片的路径                //图片首先上传至目录下                FileUpload1.SaveAs(Server.MapPath("touxiang") + "/" + Rename + "." + type);//将图片以相对路径保存,并以当前时间命名                //添加记录成功后                if (companybll.UpdateHeadImg(enCompanyInfo))                {                    Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('上传照片成功');</script>");                    DataListBind();                }                else                {                    //Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('删除照片失败,请重新上传!');</script>");                    return;                    //Response.Write("<script language='javascript'>alert('上传照片失败,请重新上传!');</script>");                }            }            else            {                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('您选择的照片格式有误,请重新选择!');</script>");                //Response.Write("<script language='javascript'>alert('您选择的照片有误,请重新选择!');</script>");            }        }        /// <summary>        /// 绑定数据        /// </summary>        public void DataListBind()        {            string UserID = Session["UserID"].ToString();            encompany = companybll.GetEntity(UserID);        }    }}

   由于服务器的大小,这里涉及一些上传图片大小的限制,也是很好的。


总结


以上就是有关头像上传的内容了,其实大家可以看到。对于问题的解决思路,十分简单。但是在涉及到一些具体的细节内容时,可能就需要一些其他方面的知识。包括绝对地址,二进制流方式的处理。但也是一步步来的,删繁就简。


0 0