把圖片存儲(chǔ)在mysql中的方法:1、獲取需要保存的圖片;2、將圖片上傳到指定路徑下的文件夾中;3、將路徑保存到變量,并將變量的值保存到數(shù)據(jù)庫(kù)中的相應(yīng)字段即可。
具體方法一般有兩種:
1、將圖片保存的路徑存儲(chǔ)到數(shù)據(jù)庫(kù);
2、將圖片以二進(jìn)制數(shù)據(jù)流的形式直接寫入數(shù)據(jù)庫(kù)字段中。
(推薦教程:mysql視頻教程)
一、保存圖片的上傳路徑到數(shù)據(jù)庫(kù):
string uppath="";//用于保存圖片上傳路徑 //獲取上傳圖片的文件名 string fileFullname = this.FileUpload1.FileName; //獲取圖片上傳的時(shí)間,以時(shí)間作為圖片的名字可以防止圖片重名 string dataName = DateTime.Now.ToString("yyyyMMddhhmmss"); //獲取圖片的文件名(不含擴(kuò)展名) string fileName = fileFullname.Substring(fileFullname.LastIndexOf("\") + 1); //獲取圖片擴(kuò)展名 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); //將路徑保存到變量,將該變量的值保存到數(shù)據(jù)庫(kù)相應(yīng)字段即可 uppath = "~/upload/" + dataName + "." + type; }
二、將圖片以二進(jìn)制數(shù)據(jù)流直接保存到數(shù)據(jù)庫(kù):
引用如下命名空間: using System.Drawing; using System.IO; using System.Data.SqlClient; 設(shè)計(jì)數(shù)據(jù)庫(kù)時(shí),表中相應(yīng)的字段類型為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 )";//操作數(shù)據(jù)庫(kù)語(yǔ)句根據(jù)需要修改 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(); 讀取: ...連接數(shù)據(jù)庫(kù)字符串省略 mycon.Open(); SqlCommand command = new SqlCommand("select stuimage from stuInfo where stuid=107", mycon);//查詢語(yǔ)句根據(jù)需要修改 byte[] image = (byte[])command.ExecuteScalar (); //指定從數(shù)據(jù)庫(kù)讀取出來(lái)的圖片的保存路徑及名字 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;
采用這兩種方式可以根據(jù)實(shí)際需求靈活選擇。