1. 程式人生 > 資料庫 >將圖片儲存在MySQL資料庫中的幾種方法

將圖片儲存在MySQL資料庫中的幾種方法

通常對使用者上傳的圖片需要儲存到資料庫中。

解決方法一般有兩種:

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;
  //採用這兩種方式可以根據實際需求靈活選擇。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對我們的支援。如果你想了解更多相關內容請檢視下面相關連結