asp.net 将图片上传到mysql数据库的方法
程序员文章站
2023-11-24 08:40:52
这是页面上的按钮单击事件 复制代码 代码如下: protected void button1_click(object sender, eventargs e) {...
这是页面上的按钮单击事件
protected void button1_click(object sender, eventargs e)
{
string tid = utils.getrandom(32);
stream mystream = this.fileupload1.postedfile.inputstream;
int length = this.fileupload1.postedfile.contentlength;
byte[] pic = new byte[length];
mystream.read(pic, 0, length);
bool flg = insert(tid, pic);
}
这是执行插入的方法
public bool insert(string tid,byte[] pic)
{
dbconn db = new dbconn();
stringbuilder sql = new stringbuilder();
sql.append("insert into teacher(tid,tphoto,tdelete) values (?tid,?pic,?flg)");
int flg = 0;
try
{
myconnection = db.getconnection();
mysqlcommand mycommand = new mysqlcommand(sql.tostring(), myconnection);
mycommand.parameters.add(new mysqlparameter("?tid", mysqldbtype.string, 32));
mycommand.parameters["?tid"].value = tid;
mycommand.parameters.add(new mysqlparameter("?pic", mysqldbtype.blob));
mycommand.parameters["?pic"].value = pic;
mycommand.parameters.add(new mysqlparameter("?flg", mysqldbtype.int16));
mycommand.parameters["?flg"].value = 0;
myconnection.open();
flg = mycommand.executenonquery();
}
catch (exception ex)
{
return false;
}
finally
{
if (myconnection != null)
{
myconnection.close();
}
}
if (flg > 0)
{
return true;
}
return false;
}
复制代码 代码如下:
protected void button1_click(object sender, eventargs e)
{
string tid = utils.getrandom(32);
stream mystream = this.fileupload1.postedfile.inputstream;
int length = this.fileupload1.postedfile.contentlength;
byte[] pic = new byte[length];
mystream.read(pic, 0, length);
bool flg = insert(tid, pic);
}
这是执行插入的方法
复制代码 代码如下:
public bool insert(string tid,byte[] pic)
{
dbconn db = new dbconn();
stringbuilder sql = new stringbuilder();
sql.append("insert into teacher(tid,tphoto,tdelete) values (?tid,?pic,?flg)");
int flg = 0;
try
{
myconnection = db.getconnection();
mysqlcommand mycommand = new mysqlcommand(sql.tostring(), myconnection);
mycommand.parameters.add(new mysqlparameter("?tid", mysqldbtype.string, 32));
mycommand.parameters["?tid"].value = tid;
mycommand.parameters.add(new mysqlparameter("?pic", mysqldbtype.blob));
mycommand.parameters["?pic"].value = pic;
mycommand.parameters.add(new mysqlparameter("?flg", mysqldbtype.int16));
mycommand.parameters["?flg"].value = 0;
myconnection.open();
flg = mycommand.executenonquery();
}
catch (exception ex)
{
return false;
}
finally
{
if (myconnection != null)
{
myconnection.close();
}
}
if (flg > 0)
{
return true;
}
return false;
}