一、把图片保存到数据库,这里要分成两步:
1)把图片存入到一个字节数组中(byte[])这里要把它的数据读入到数组中:
/// <summary>
/// 用图片控件取到它的图片数据流
/// </summary>
/// <param name="change_pics">控件HtmlInputFile的控件名</param>
/// <param name="msg">返回的信息</param>
/// <param name="FileLength">文件大小</param>
/// <returns></returns>
public byte[] IntoPics(HtmlInputFile change_pics,out string msg,out int FileLength)
{
FileLength=0;
string FileName=change_pics.Value;
FileLength=change_pics.PostedFile.ContentLength;
if(FileLength==0)
{
msg="NoFile";
}
else
{
string exName=FileName.Substring(FileName.LastIndexOf(".")+1);
if(exName=="jpg"||exName=="bmp"||exName=="gif"||exName=="JPG"||exName=="BMP"||exName=="GIF")
{
if(FileLength>204800)
{
msg="TooBigFile";
}
else
{
// string ImgeName=DateTime.Now.ToString()+"."+exName;//文件名
byte [] Filebyte=new byte[FileLength];//图片数据
Stream infostream=change_pics.PostedFile.InputStream;
infostream.Read(Filebyte,0,FileLength);
msg="RightFile";
return Filebyte;
}
}
else
{
msg="ErroyLastName";
}
}
return null;
}
2)把这个字节流的数组存入到数据库,
string M;
int Len;
byte[] pic=this.IntoPics(change_pics,out M,out Len);
string sql="insert into 表(列1,列2,图片列) values('第一列数据','第二列数据',@Image)";
SqlCommand com=new SqlCommand(sql,sqlconn);
com.Parameters.Add("@Image",SqlDbType.Binary,Len).Value=pic;
com.ExecuteNonQuery();//执行SQL
这样就把图片作为二进制的数据存入了数据库,
接下来是把它读出来:
二、读出图片:
注意;这是是将图片读出到页面上,让它显示出来。所以肯定要新建一个页面(UserPic):
先定义一句SQL
string strcom="SELECT HeadSelf FROM Users WHERE Userid='"+Request["Userid"]+"'";
SqlCommand com=new SqlCommand(strcom,sqlconn);//和下面的一行可以在类中建个方法
SqlDataReader read=com.ExecuteReader();
while(dr.Read())
{
Response.BinaryWrite((byte[])dr["HeadSelf"]);
}
这样,在别的地方如果要显示图片,可以在页面上放一个Image控件,再把它的ImageUrl 属性改到这个页面上来,如:
User_Image.ImageUrl="UserPic.aspx?Userid="+UserID;
转载于:https://www.cnblogs.com/pointdeng/archive/2008/02/01/1060902.html