将图片贮存在MySQL数据库中的几种要领
发布时间:05/13 来源:未知 浏览:
关键词:
平常对会员上传的图片需要保留到数据库中。
解决要领个别有两种:
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; //采纳这两种方式可以依据现实需求灵活选中。
总结
以上就是这篇文章的全部内容了,但愿本文的内容对大家的学习或者工作拥有一定的参考学习价值,感谢大家对脚本之家的支撑。要是你想理解更多相干内容请查看下面相干链接