cmd.CommandText = "SELECT picture , filename FROM pic ";
SqlDataReader dr = cmd.ExecuteReader();
byte[] img = null;
while (dr.Read())
{
MyData data = new MyData();
img = (byte[]) dr["picture"];
MemoryStream str = new MemoryStream();
str.Write(img, 0, img.Length);
Bitmap bit = new Bitmap(str);
data.img = bit;
data.filename = (string) dr["filename"];
myDataList.Add(data);
}
2011年11月16日 星期三
ASP.NET C# 從資料庫(MSSQL)讀出圖檔
ASP.NET C# 將檔圖存入資料庫(MSSQL)
// 讀取二進制檔
public byte[] ReadFile(string path)
{
byte[] data = null;
FileInfo fInfo = new FileInfo(path);
long length = fInfo.Length;
FileStream fStream = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)length);
return data;
}
// --讀取檔案轉成二進制字資料, 並存入資料庫裡--
imageData = ReadFile(k.ImageLocation);
// -- 新增資料的Sql語句 --
cmd.CommandText = "INSERT INTO pic ( filename, picture , in_time ) " +
" VALUES ( @imagePath, @imageData, @inTime ) ";
// --設定輸入參數--
cmd.Parameters.Add("@imagePath", SqlDbType.NVarChar).Value = k.Name;
cmd.Parameters.Add("@imageData", SqlDbType.Image).Value = imageData;
cmd.Parameters.Add("@inTime", SqlDbType.SmallDateTime).Value = DateTime.Now.Date;
// --設定輸入參數--
cmd.ExecuteNonQuery(); // 執行寫入作業
public byte[] ReadFile(string path)
{
byte[] data = null;
FileInfo fInfo = new FileInfo(path);
long length = fInfo.Length;
FileStream fStream = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)length);
return data;
}
// --讀取檔案轉成二進制字資料, 並存入資料庫裡--
imageData = ReadFile(k.ImageLocation);
// -- 新增資料的Sql語句 --
cmd.CommandText = "INSERT INTO pic ( filename, picture , in_time ) " +
" VALUES ( @imagePath, @imageData, @inTime ) ";
// --設定輸入參數--
cmd.Parameters.Add("@imagePath", SqlDbType.NVarChar).Value = k.Name;
cmd.Parameters.Add("@imageData", SqlDbType.Image).Value = imageData;
cmd.Parameters.Add("@inTime", SqlDbType.SmallDateTime).Value = DateTime.Now.Date;
// --設定輸入參數--
cmd.ExecuteNonQuery(); // 執行寫入作業
訂閱:
意見 (Atom)