发布网友 发布时间:2022-04-13 06:55
共5个回答
懂视网 时间:2022-04-13 11:17
图片通过asp.net上传到mysql数据库的方法
这是页面上的按钮单击事件
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;
}热心网友 时间:2022-04-13 08:25
在得到图片的时候自己写一个方法将图片转化成二进制流的形式存入数据库:
private byte[] ConvertPicture()
{
string path = FileUpload1.FileName //记录图片所在的路径
byte[] byteImage = null; // 初始化一个字节数组储存图片
FileStream FStream = new FileStream(path , FileMode.Open, FileAccess.Read); //将图片以文件流的形式进行保存
BinaryReader BReader = new BinaryReader(FStream);
byteImage = BReader.ReadBytes((int)FStream.Length);
BReader.Close();
FStream.Close();
return byteImage;
}
在数据库中读取出二进制流的图片:
byte[] bytes = model.EmployeeImage;
MemoryStream ms = new MemoryStream(bytes);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
this.Image1 = img;热心网友 时间:2022-04-13 09:43
我不建议将图片存到数据库中,
一般我们的做法都是将图片存到本地或者序列化到本地某个文件夹,
然后数据库中存这个图片的路径!热心网友 时间:2022-04-13 11:17
string name = FileUpload1.PostedFile.FileName;
string type=name .Substring (name .LastIndexOf (".")+1);
FileStream fs = File.OpenRead(name);
byte[] content=new byte [fs.Length];
fs.Read(content, 0, content.Length);
fs.Close();
SqlConnection cn = new SqlConnection("server=.;uid=sa;pwd=****;database=za");
SqlCommand cm = new SqlCommand("insert into myimage(imagedata) values(@imagedata)",cn);
cn.Open();
if (type == "jpg" || type == "gif" || type == "bmp" || type == "png")
{
cm.Parameters.Add("@imagedata", SqlDbType.Image);
cm.Parameters["@imagedata"].Value = content;
cm.ExecuteNonQuery();
cn.Close();
}热心网友 时间:2022-04-13 13:09
先转换成二进制