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

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();
     }

你可能感兴趣的:(sqlserver2005)