保存图片到DB(SqlServer2005)并显示

本文介绍了使用ASP.NET进行文件上传的方法,并展示了如何将上传的文件保存到数据库中及从数据库读取并显示图片的过程。

protected void Button2_Click(object sender, EventArgs e)//保存
    {

            HttpPostedFile   upFile   =   File1.PostedFile; 
           
       
            int   iFileLength   =   upFile.ContentLength;  
            try
            {  
                if(iFileLength   ==   0)
                {  
                    Response.Write( "请选择要上传的文件!");  
                }
                else
                {
                    Byte[]   FileByteArray   =   new   Byte[iFileLength];  
                    Stream StreamObject   =   upFile.InputStream;   
                    
                   

                    StreamObject.Read(FileByteArray,   0,   iFileLength); 

                    SqlConnection conn = new SqlConnection("server=.;database=eHR;uid=sa;pwd=1234;");
                    SqlCommand cmd = new SqlCommand("insert into [imageTable] values(@image)", conn);
                    cmd.Parameters.Add("@Image",   SqlDbType.Binary,   iFileLength).Value   =   FileByteArray;
                    conn.Open();  
                    cmd.ExecuteNonQuery();  
                    conn.Close();  
                    Response.Write("OK!你已经成功上传了类型的文件");
                }

            }
            catch(Exception ex)
            {
                 Response.Write(ex.ToString());
            }
            Image1.Src=File1.Value;
          
        }

 

 protected void Button3_Click(object sender, EventArgs e) //输出
    {
      
       string connString = "server=.;database=eHR;uid=sa;pwd=1234";
       SqlConnection conn = new SqlConnection(connString);
       string selString = "select top 1 imagedata from imageTable";
       SqlCommand comm = new SqlCommand(selString,conn);
       conn.Open();
       SqlDataReader dr = comm.ExecuteReader();//读出数据
       dr.Read();//读一行
       //输出图片文件二进制数据
       Response.BinaryWrite((byte[])dr["imagedata"]);
       Response.End();
       dr.Close();
       conn.Close();
     }

转载于:https://www.cnblogs.com/Gsun/archive/2009/03/11/1408331.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值