当前位置: 移动技术网 > IT编程>数据库>Mysql > 将图片储存在MySQL数据库中的几种方法

将图片储存在MySQL数据库中的几种方法

2019年03月19日  | 移动技术网IT编程  | 我要评论

通常对用户上传的图片需要保存到数据库中。

解决方法一般有两种:

1、将图片保存的路径存储到数据库;

2、将图片以二进制数据流的形式直接写入数据库字段中。

以下为具体方法:

一、保存图片的上传路径到数据库:

  string uppath="";//用于保存图片上传路径
  //获取上传图片的文件名
  string filefullname = this.fileupload1.filename;
  //获取图片上传的时间,以时间作为图片的名字可以防止图片重名
  string dataname = datetime.now.tostring("yyyymmddhhmmss");
  //获取图片的文件名(不含扩展名)
  string filename = filefullname.substring(filefullname.lastindexof("\\") + 1);
  //获取图片扩展名
  string type = filefullname.substring(filefullname.lastindexof(".") + 1);
  //判断是否为要求的格式
  if (type == "bmp" || type == "jpg" || type == "jpeg" || type == "gif" || type == "jpg" || type == "jpeg" || type == "bmp" || type == "gif")
  {
   //将图片上传到指定路径的文件夹
   this.fileupload1.saveas(server.mappath("~/upload") + "\\" + dataname + "." + type);
   //将路径保存到变量,将该变量的值保存到数据库相应字段即可
   uppath = "~/upload/" + dataname + "." + type;
  }

二、将图片以二进制数据流直接保存到数据库:

引用如下命名空间:

    using system.drawing;
  using system.io;
  using system.data.sqlclient;
  设计数据库时,表中相应的字段类型为iamge
  保存:
  //图片路径
  string strpath = this.fileupload1.postedfile.filename.tostring ();
  //读取图片
  filestream fs = new system.io.filestream(strpath, filemode.open, fileaccess.read);
  binaryreader br = new binaryreader(fs);
  byte[] photo = br.readbytes((int)fs.length);
  br.close();
  fs.close();
  //存入
  sqlconnection myconn = new sqlconnection("data source=.;initial catalog=stumanage;user id=sa;password=123");
  string strcomm = " insert into stuinfo(stuid,stuimage) values(107,@photobinary )";//操作数据库语句根据需要修改
  sqlcommand mycomm = new sqlcommand(strcomm, myconn);
  mycomm.parameters.add("@photobinary", sqldbtype.binary, photo.length);
  mycomm.parameters["@photobinary"].value = photo;
  myconn.open();
  if (mycomm.executenonquery() > 0)
  {
   this.label1.text = "ok";
  }
  myconn.close();
  读取:
  ...连接数据库字符串省略
  mycon.open();
  sqlcommand command = new
  sqlcommand("select stuimage from stuinfo where stuid=107", mycon);//查询语句根据需要修改
  byte[] image = (byte[])command.executescalar ();
  //指定从数据库读取出来的图片的保存路径及名字
  string strpath = "~/upload/zhangsan.jpg";
  string strphotopath = server.mappath(strpath);
  //按上面的路径与名字保存图片文件
  binarywriter bw = new binarywriter(file.open(strphotopath,filemode.openorcreate));
  bw.write(image);
  bw.close();
  //显示图片
  this.image1.imageurl = strpath;
  //采用这两种方式可以根据实际需求灵活选择。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网