asp.net FileUpload 控件上传文件 以二进制的形式存入数据库并将图片显示出来

时间:2023-03-09 06:45:23
asp.net FileUpload 控件上传文件 以二进制的形式存入数据库并将图片显示出来

图片上传事件代码如下所示:

         byte[] binary = upload.FileBytes;
StringBuilder sqlStrSb = new StringBuilder();
sqlStrSb.Append("update info set Thumb=?Imgwhere Id=200");
string mySqlConStr = "Host=localhost; uid=root; pwd=123; DataBase=db";
MySqlConnection mySqlCon = new MySqlConnection(mySqlConStr);
mySqlCon.Open();
MySqlCommand mySqlCom = new MySqlCommand();
mySqlCom.CommandText = sqlStrSb.ToString();
mySqlCom.Connection = mySqlCon;
MySqlParameter par = new MySqlParameter("?Img", MySqlDbType.VarBinary);
par.Value = binary;
mySqlCom.Parameters.Add(par);
int afn = mySqlCom.ExecuteNonQuery();
mySqlCon.Close();

注:转为二进制存入数据库的时候必须使用 MySqlDbType.VarBinary 或者 MySqlDbType.Binary 进行数据类型的限定。

图片显示代码如下所示:

             string mySqlConStr = "Host=host;uid=root;pwd=123;DataBase=db;";
string sqlStr = "select ThumbData from info where Id=200;";
MySqlConnection mySqlCon = new MySqlConnection(mySqlConStr);
mySqlCon.Open();
MySqlCommand mySqlComd = new MySqlCommand();
mySqlComd.CommandText = sqlStr;
mySqlComd.Connection = mySqlCon;
MySqlDataAdapter mySqlSda = new MySqlDataAdapter();
mySqlSda.SelectCommand = mySqlComd;
DataSet ds = new DataSet();
mySqlSda.Fill(ds);
if (ds.Tables.Count > )
{
byte[] dataByte = (byte[])ds.Tables[].Rows[][];
Response.BinaryWrite(dataByte);
Response.Flush();
Response.End();
}
mySqlCon.Close();

页面显示部分:

         <img src="ShowImage.aspx" />