数据库:Sql Server 2005
字段:image_file 类型:image
前台控件:FileUpLoad(fuImage)、上传button(btnUpload)、查询button、GridVew
图片上传代码:
protected void btnUpload_Click(object sender, EventArgs e)
{
byte[] imgBinaryData = this.fuImage.FileBytes;
{
string sql = "insert into image(image_file) values (@img)";
string strconn ="Data Source=SMARTGUOLEI;Initial Catalog=web;Persist Security Info=True;User ID=sa;Password=sa;";
SqlConnection sqlConn = new SqlConnection(strconn);
SqlCommand sqlComm = new SqlCommand(sql, sqlConn);
sqlComm.Parameters.Add("@img", SqlDbType.Image);//添加参数
sqlComm.Parameters["@img"].Value = imgBinaryData;//为参数赋值
sqlConn.Open();
sqlComm.ExecuteNonQuery();
sqlConn.Close();
Response.Write("<script language='javascript'>alert('保存成功!')</script>");
}
此代码应该是运行正常,因为我通过SqlDataSource控制的配置数据源的功能,在最后完成的那一步,通过查询的功能看到上传上来的图像。
数据查询代码:
protected void Button1_Click(object sender, EventArgs e)
{
string s;
s = "select * from image";
OleDbConnection Conn = null;
DataSet ds = null;
string strConn = "Data Source=SMARTGUOLEI;Initial Catalog=web;Persist Security Info=True;User ID=sa;Password=sa;Provider=SQLOLEDB.1;";
Conn = new OleDbConnection(strConn); //实例化一个连接
OleDbCommand Cmd = new OleDbCommand(s);
OleDbDataAdapter ODA = new OleDbDataAdapter(Cmd); //实例化一个数据适配器
ODA.SelectCommand.Connection = Conn;
Conn.Open();//记得要打开连接
//ODA.SelectCommand.CommandText=s;
ds = new DataSet();
ODA.Fill(ds, "image");
this.GridView1.DataSource = ds;
this.GridView1.DataBind();
}
此代码应该是运行正常的,因为我在数据库表的设计上,加了一个int编号主键(自动增值 ),在GridView显示时,可以将那个编号查询出来。
GridView的前台代码:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:ImageField DataImageUrlField="image_file">
</asp:ImageField>
</Columns>
</asp:GridView>