原文: Saving and Displaying Photos in SQL Server using ASP.NET and FileUpload Control
主要是介紹在VS2005中如何將圖片直接存入到資料庫,當然利用了FileUpload這個控制項
下面我把主要代碼貼上來(已經測試過了,沒什麼問題):
Save:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
using(BinaryReader reader = new BinaryReader(FileUpload1.PostedFile.InputStream))
{
byte[] image = reader.ReadBytes(FileUpload1.PostedFile.ContentLength);
using (SqlConnection conn = new SqlConnection("server=.;database=IBatisNet;uid=sa;pwd="))
{
using (SqlCommand command = conn.CreateCommand())
{
command.CommandText = @"INSERT INTO photo (photo) VALUES (@photo)";
command.Parameters.AddWithValue("@photo", image);
conn.Open();
command.ExecuteNonQuery();
}
}
}
}
}
Display:
protected void Button2_Click(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "image/jpeg";
using (SqlConnection conn = new SqlConnection("server=.;database=IBatisNet;uid=sa;pwd="))
{
using (SqlCommand command = conn.CreateCommand())
{
command.CommandText = "select top 1 photo from photo";
conn.Open();
byte[] imageData = (byte[])command.ExecuteScalar();
Response.BinaryWrite(imageData);
}
}
}