技术开发 频道

ASP.NET 2.0编程技巧之用Response对象输出图像


三、 事件设计

  示例工程中的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{ ///创建链接 3SqlConnection myConnection = new SqlConnection( 4ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRING"].ConnectionString); 5///定义SQL语句 6string cmdText = "SELECT * FROM PictureTab WHERE PictureID='1'"; 7///创建Command 8SqlCommand myCommand = new SqlCommand(cmdText,myConnection); 9///定义DataReader 10SqlDataReader dr = null; 11try 12{ ///打开链接 13myConnection.Open(); 14///读取数据 15dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection); 16} 17catch(SqlException ex) 18{ ///抛出异常 19throw new Exception(ex.Message,ex); 20} 21///定义保存数据的字节数组 22byte[] Data = null; 23while(dr.Read()) 24{ ///读取数据 25Data = (byte[])dr["Data"]; 26Response.ContentType = dr["Type"].ToString(); 27} 28dr.Close(); 29//显示图片数据 30this.EnableViewState = false; 31///输出文件头 32Response.AppendHeader("Content-Length",Data.Length.ToString()); 33///输出文件的数据 34Response.BinaryWrite(Data); 35///结束输出 36Response.End(); 37}
0
相关文章