首先、在WEBFORM的HTML中将FORM的属性修改为如下:
<form id="Form1" method="post"enctype="multipart/form-data" runat="server">
然后在保存到数据库的按钮中写
string imgtype = myFile.PostedFile.ContentType;
string imgtitle = TextBox1.Text;
Stream imgdatastream = myFile.PostedFile.InputStream;
int imgdatalen = myFile.PostedFile.ContentLength;
byte[] imgdata = new byte[imgdatalen];
int n = imgdatastream.Read(imgdata,0,imgdatalen);
string connstr="server=new;uid=sa;pwd=sa;database=dianxinkapin";//
SqlConnection connection = new SqlConnection(connstr);
SqlCommand command = new SqlCommand("INSERT INTO ImageStore(id,imgtitle,imgtype,imgdata) VALUES (@id, @imgtitle, @imgtype,@imgdata )", connection );
command.Parameters.Add("@id", SqlDbType.VarChar,50).Value= TextBox1.Text;
command.Parameters.Add("@imgtitle", SqlDbType.VarChar,50).Value= TextBox2.Text;
command.Parameters.Add("@imgdata", SqlDbType.Image).Value= imgdata;
command.Parameters.Add("@imgtype", SqlDbType.VarChar,50).Value= imgtype;
connection.Open();
int numRowsAffected = command.ExecuteNonQuery();
connection.Close();
if(myFile.PostedFile!=null)
{
string nam = myFile.PostedFile.FileName ;
int i= nam.LastIndexOf("\\") ;
string newnm =nam.Substring(i) ;
if(File.Exists(Server.MapPath("image\\")+newnm))//判断文件是否存在
{
Label1.Text="此文件名在服务器上已存在!!";
}
myFile.PostedFile.SaveAs(Server.MapPath("image\\")+newnm) ;
TextBox1.Text=myFile.PostedFile.FileName;
TextBox2.Text=myFile.PostedFile.ContentType ;
TextBox3.Text=myFile.PostedFile.ContentLength.ToString();
}
在浏览图片的按钮下写
string connstr="server=new;uid=sa;pwd=sa;database=dianxinkapin";
string sql="SELECT imgdata, imgtype FROM ImageStore WHERE id ='"+TextBox1.Text+"'";
SqlConnection connection = new SqlConnection(connstr);
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if(dr.Read())
{
Response.ContentType = dr["imgtype"].ToString();
Response.BinaryWrite( (byte[]) dr["imgdata"] );
}
connection.Close();