Saving and Displaying Photos in SQL Server using ASP.NET and FileUpload Control
原文: 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();
}
}
}
}
}
{
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);
}
}
}
{
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);
}
}
}
posted on 2006-07-27 12:09 Daniel Pang 阅读(1283) 评论(0) 编辑 收藏 举报