Create table PhotoTest
(
ID int identity(1,1) primary key,
Photo image
)
<connectionStrings>
<add name="ConnSqlStr" connectionString="Data Source = (local); User ID = sa; password=***; DataBase = Test " providerName="System.Data.SqlClient"/>
</connectionStrings>
CS代码
protected void Button1_Click(object sender, EventArgs e)
{
string conn = ConfigurationManager.ConnectionStrings["ConnSqlStr"].ToString();
SqlConnection con = new SqlConnection(conn);
con.Open();
Stream photo = File1.PostedFile.InputStream;
int ImageSize=File1.PostedFile.ContentLength;
byte[] ImageContent=new byte[ImageSize];
photo.Read(ImageContent,0,ImageSize);
string sql = "Insert into PhotoTest values(@i)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("@i", SqlDbType.Image, (int)photo.Length);
cmd.Parameters["@i"].Value = ImageContent;
cmd.ExecuteNonQuery();
con.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
string conn = ConfigurationManager.ConnectionStrings["ConnSqlStr"].ToString();
SqlConnection con = new SqlConnection(conn);
con.Open();
string sql = "select Photo from PhotoTest where id = 1";
SqlCommand cmd = new SqlCommand(sql, con);
byte[] fileData = (byte[])cmd.ExecuteScalar();
System.IO.MemoryStream ms = new System.IO.MemoryStream(fileData);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
con.Close();
}