當前位置:首頁 » 圖片效果 » 怎樣把圖片保存到資料庫里
擴展閱讀
ix25時間不對怎樣調 2025-02-12 03:54:32
在智學網上怎樣查原試卷 2025-02-12 03:37:26
網上怎樣認證養老資格 2025-02-12 03:28:10

怎樣把圖片保存到資料庫里

發布時間: 2023-06-08 19:05:16

A. 如何把圖片存到資料庫中

通常對用戶上傳的圖片需要保存到資料庫中。解決方法一般有兩種:一種是將圖片保存的路徑存儲到資料庫;另一種是將圖片以二進制數據流的形式直接寫入資料庫欄位中。以下為具體方法:
一、保存圖片的上傳路徑到資料庫:
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;
採用倆種方式可以根據實際需求靈活選擇。

B. 圖片如何存放在oracle資料庫

1、使用blob將圖片保存為二進制格式,(可以用瀏覽器來轉換)隨後用base64編碼來保存圖片,再將base64編碼保存進資料庫的clob類型欄位上。

C. 怎麼把圖片保存到資料庫里

把你的圖片放在你項目的根目錄下面,把路徑保存在資料庫中。。資料庫一般不是用來放圖片的,如果你是做網站,你的空間根本不夠放那麼多。。建議你還是在資料庫中保存你圖片的地址