.NET 图片存到数据库并显示到网页中

时间:2015/12/3 16:47:00来源:互联网 作者:flyso 点击: 954 次

1.将图片转换为二进制

     public static Byte[] SetImgToByte(string imgPath)     {          FileStream file = new FileStream(imgPath, FileMode.Open, FileAccess.Read);           Byte[] byteData = new Byte[file.Length];           file.Read(byteData, 0, byteData.Length);  
          file.Close();
          return byteData;
    }
2.asp.net把图片转换成Byte[]形式存到数据库中

    string ImgPath = FileUpload.PostedFile.FileName;//图片路径
            string ImgName = ImgPath.Substring(ImgPath.LastIndexOf("\\") + 1);//图片名称
            string ImgExtend = ImgPath.Substring(ImgPath.LastIndexOf(".") + 1).ToLower();//图片格式
            if (!(ImgExtend == "bmp" || ImgExtend == "jpg" || ImgExtend == "gif"))
            {
                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "sendok", "alert('上传图片的格式不正确!

'    )", true);
                return;
            }
            int FileLen = this.fu1.PostedFile.ContentLength;//图片长度
            if (FileLen > 204800)
            {
                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "sendok", "alert('上传图片不能大于200k!

    ')", true);
                return;
            }
            Byte[] FileData = new Byte[FileLen];
            HttpPostedFile hp = fu1.PostedFile;//创建访问客户端上传文件的对象
            Stream sr = hp.InputStream;//创建数据流对象
            sr.Read(FileData, 0, FileLen);//将图片数据放到FileData数组对象实例中,其中0代表数组指针的起始位置,FileLen表示要读取流的长度(指针的结素位置)
    Userphoto up=new Userphoto();
    up.phtot=FileData

3.asp.net 从数据库读取图片并显示到界面上

     曲线救国

    一个页面的HTML文件

    <asp:Image Width="280px" Height="260px" ID="Image3" ImageUrl='<%#"~/Regulation/ShowImg.aspx?id="+Eval("id") %>'

    另一个页面的后台代码

    public partial class Regulation_ShowImg : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["id"]!=null)
            {
                int id = Convert.ToInt32(Request.QueryString["id"]);
                String sql = "select pictrue from progressfile where id = " + id;
                object o = myWeb.DAL.Regulation.DBHelper.getScalar(sql);

                Response.ContentType = "application/octet-stream";
                Response.BinaryWrite((Byte[])o);
                Response.End();
            }
        }
    }

Copyright © 2005 - 2016 flyso.cn. 飞搜 版权所有 鄂ICP备11002783号-3