將圖片儲存在MySQL數(shù)據(jù)庫中的幾種方法
通常對用戶上傳的圖片需要保存到數(shù)據(jù)庫中。
解決方法一般有兩種:
1、將圖片保存的路徑存儲到數(shù)據(jù)庫;
2、將圖片以二進(jìn)制數(shù)據(jù)流的形式直接寫入數(shù)據(jù)庫字段中。
以下為具體方法:
一、保存圖片的上傳路徑到數(shù)據(jù)庫:
string uppath="";//用于保存圖片上傳路徑
//獲取上傳圖片的文件名
string fileFullname = this.FileUpload1.FileName;
//獲取圖片上傳的時間,以時間作為圖片的名字可以防止圖片重名
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ù)庫相應(yīng)字段即可
uppath = "~/upload/" + dataName + "." + type;
}
二、將圖片以二進(jìn)制數(shù)據(jù)流直接保存到數(shù)據(jù)庫:
引用如下命名空間:
using System.Drawing;
using System.IO;
using System.Data.SqlClient;
設(shè)計數(shù)據(jù)庫時,表中相應(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ù)庫語句根據(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ù)庫字符串省略
mycon.Open();
SqlCommand command = new
SqlCommand("select stuimage from stuInfo where stuid=107", mycon);//查詢語句根據(jù)需要修改
byte[] image = (byte[])command.ExecuteScalar ();
//指定從數(shù)據(jù)庫讀取出來的圖片的保存路徑及名字
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í)際需求靈活選擇。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對本站的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信