三、 事件设计
示例工程中的DispImage.aspx页面在其初始化函数Page_Load(object sender,EventArgs e)中使用Response对象输出一幅图像—该图像存储在SQL Server 2005 Express Edition数据库中,并用二进制表示。
在代码中,我们首先从数据库PictureDB的表格PictureTab中获取一个ID值为1的图片,然后使用byte数组Data保存图片的数据。然后,我们可以基于如下步骤来输出相应的图像:
1. 设置Response对象的输出类型;
2. 输出图像的文件头;
3. 输出图像的二进制数据;
4. 结束输出。如果图片太大,还可以使用输出缓冲的方法。
函数Page_Load(object sender,EventArgs e)的程序代码如下:
1protected void Page_Load(object sender,EventArgs e) 2
...{ /**////创建链接 3
SqlConnection myConnection = new SqlConnection( 4
ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRING"].ConnectionString); 5
/**////定义SQL语句 6
string cmdText = "SELECT * FROM PictureTab WHERE PictureID='1'"; 7
/**////创建Command 8
SqlCommand myCommand = new SqlCommand(cmdText,myConnection); 9
/**////定义DataReader 10
SqlDataReader dr = null; 11
try 12
...{ /**////打开链接 13
myConnection.Open(); 14
/**////读取数据 15
dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection); 16
} 17
catch(SqlException ex) 18
...{ /**////抛出异常 19
throw new Exception(ex.Message,ex); 20
} 21
/**////定义保存数据的字节数组 22
byte[] Data = null; 23
while(dr.Read()) 24
...{ /**////读取数据 25
Data = (byte[])dr["Data"]; 26
Response.ContentType = dr["Type"].ToString(); 27
} 28
dr.Close(); 29
//显示图片数据 30
this.EnableViewState = false; 31
/**////输出文件头 32
Response.AppendHeader("Content-Length",Data.Length.ToString()); 33
/**////输出文件的数据 34
Response.BinaryWrite(Data); 35
/**////结束输出 36
Response.End(); 37
}
