图片上传事件代码如下所示:
1 byte[] binary = upload.FileBytes; 2 StringBuilder sqlStrSb = new StringBuilder(); 3 sqlStrSb.Append("update info set Thumb=?Imgwhere Id=200"); 4 string mySqlConStr = "Host=localhost; uid=root; pwd=123; DataBase=db"; 5 MySqlConnection mySqlCon = new MySqlConnection(mySqlConStr); 6 mySqlCon.Open(); 7 MySqlCommand mySqlCom = new MySqlCommand(); 8 mySqlCom.CommandText = sqlStrSb.ToString(); 9 mySqlCom.Connection = mySqlCon; 10 MySqlParameter par = new MySqlParameter("?Img", MySqlDbType.VarBinary); 11 par.Value = binary; 12 mySqlCom.Parameters.Add(par); 13 int afn = mySqlCom.ExecuteNonQuery(); 14 mySqlCon.Close();
注:转为二进制存入数据库的时候必须使用 MySqlDbType.VarBinary 或者 MySqlDbType.Binary 进行数据类型的限定。
图片显示代码如下所示:
1 string mySqlConStr = "Host=host;uid=root;pwd=123;DataBase=db;"; 2 string sqlStr = "select ThumbData from info where Id=200;"; 3 MySqlConnection mySqlCon = new MySqlConnection(mySqlConStr); 4 mySqlCon.Open(); 5 MySqlCommand mySqlComd = new MySqlCommand(); 6 mySqlComd.CommandText = sqlStr; 7 mySqlComd.Connection = mySqlCon; 8 MySqlDataAdapter mySqlSda = new MySqlDataAdapter(); 9 mySqlSda.SelectCommand = mySqlComd; 10 DataSet ds = new DataSet(); 11 mySqlSda.Fill(ds); 12 if (ds.Tables.Count > 0) 13 { 14 byte[] dataByte = (byte[])ds.Tables[0].Rows[0][0]; 15 Response.BinaryWrite(dataByte); 16 Response.Flush(); 17 Response.End(); 18 } 19 mySqlCon.Close();
页面显示部分:
1 <img src="ShowImage.aspx" />