现在的位置: 首页 > 综合 > 正文

asp.net 上传图片(字节)到mysql数据库

2013年10月17日 ⁄ 综合 ⁄ 共 1546字 ⁄ 字号 评论关闭

这是页面上的按钮单击事件

 

  1. protected void Button1_Click(object sender, EventArgs e)
  2.     {
  3.         string tid = Utils.getRandom(32);
  4.         Stream mystream = this.FileUpload1.PostedFile.InputStream;
  5.         int length = this.FileUpload1.PostedFile.ContentLength;
  6.         byte[] pic = new byte[length];
  7.         mystream.Read(pic, 0, length);
  8.         bool flg = insert(tid, pic);
  9.     }

这是执行插入的方法

  1. public bool insert(string tid,byte[] pic) 
  2.     {
  3.         DBConn db = new DBConn();
  4.         StringBuilder sql = new StringBuilder();
  5.         sql.Append("insert into teacher(TID,TPHOTO,TDELETE) values (?tid,?pic,?flg)");
  6.         int flg = 0;
  7.         try
  8.         {
  9.             myConnection = db.getConnection();
  10.             MySqlCommand myCommand = new MySqlCommand(sql.ToString(), myConnection);
  11.             myCommand.Parameters.Add(new MySqlParameter("?tid", MySqlDbType.String, 32));
  12.             myCommand.Parameters["?tid"].Value = tid;
  13.             myCommand.Parameters.Add(new MySqlParameter("?pic", MySqlDbType.Blob));
  14.             myCommand.Parameters["?pic"].Value = pic;
  15.             myCommand.Parameters.Add(new MySqlParameter("?flg", MySqlDbType.Int16));
  16.             myCommand.Parameters["?flg"].Value = 0;
  17.             myConnection.Open();
  18.             flg = myCommand.ExecuteNonQuery();
  19.         }
  20.         catch (Exception ex)
  21.         {
  22.             return false;
  23.         }
  24.         finally
  25.         {
  26.             if (myConnection != null)
  27.             {
  28.                 myConnection.Close();
  29.             }
  30.         }
  31.         if (flg > 0)
  32.         {
  33.             return true;
  34.         }
  35.         return false;
  36.     }

抱歉!评论已关闭.