具体方法一般有两种:
1、将图片保存的路径存储到数据库;
2、将图片以二进制数据流的形式直接写入数据库字段中。
(推荐教程:mysql视频教程)
一、保存图片的上传路径到数据库:
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 = newsqlcommand("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;
采用这两种方式可以根据实际需求灵活选择。
相关推荐:mysql教程
以上就是如何把图片存储在mysql中的详细内容。
