//寫入圖片到資料庫中
private void WriteImage()
{
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "insert into images(image,type) values(@image,@type)";
comm.CommandType = CommandType.Text;
SqlParameter param = comm.Parameters.Add("@image",SqlDbType.Image);
param.Value = ReadFile();
param = comm.Parameters.Add("@type",SqlDbType.NVarChar);
param.Value = GetContentType(new FileInfo(fileName).Extension.Remove(0,1));
if(comm.executenonquery() == 1)
Response.Write("Successful");
else
Response.Write("Fail");
conn.Close();
}
//從資料庫中讀取圖片
private void ReadImage()
{
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "select image,type from images";
comm.CommandType = CommandType.Text;
sqldatareader reader = comm.ExecuteReader();
while(reader.Read())
{
Response.ContentType = reader["type"].ToString();//讀寫類型 一定要設定 否則瀏覽器會當作文本輸出
Response.BinaryWrite((byte[])reader["image"]);//圖片資料
}
response.write("successful");
Response.End();
conn.close();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//其他自訂方法如下:
//串連資料庫
private void ConnectDB()
{
string connStr = "Initial Catalog=;Data Source=;User ID=sa;Password=;";
conn = new SqlConnection(connStr);
conn.Open();
}
//得到檔案名稱
private string GetFile()
{
HttpPostedFile file = File1.PostedFile;
fileName = file.FileName;
return fileName;
}
//讀取檔案內容
private byte[] ReadFile()
{
FileStream file = File.OpenRead(GetFile());
byte[] content = new byte;
file.Read(content,0,content.Length);
file.Close();
return content;
}
//擷取圖片的尾碼名
private string GetContentType(string extension)
{
string type = "";
if(extension.equals("jpg") || extension.Equals("JPG"))
type = "jpeg";
else
type = extension;
return "image/"+type;
}