当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > 在ASP.NET中从SQL Server检索图片

ASP.NET
如何在ASP.NET中使用SmtpMail发送邮件
在VB.NET中利用Split和Replace函数计算字数
Attribute应用:简化ANF自定义控件初始化过程
ASP.NET 2.0移动开发入门之使用样式
ASP.NET 2.0中使用OWC生成图表
ASP.NET 2.0中控件的简单异步回调
一个无法捕获ADO.NET Dataset的内存错误
深入解读ADO.NET2.0的十大最新特性
.Net平台下的分布式缓存设计
ASP.NET全局异常处理浅析
ASP.NET 2.0中文验证码的实现
浅析.NET平台编程语言的未来走向
.net 框架程序设计收藏
使用ASP.NET MVC Futures 中的异步Action
详解.NET中的XmlReader与XmlWriter
关于.NET中的Server push技术
asp.net页面执行机制
对比JSP和ASP.NET的存储过程
.NET 4.0不会包含System.Shell.CommandLine
ASP.NET十个有效性能优化的方法

在ASP.NET中从SQL Server检索图片


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 105 ::
收藏到网摘: n/a

和存储图片相比,读取图片就要简单多了。输出一副图片我们要做的就是使用Response对象的BinaryWrite方法。

同时设置图片的格式。在这篇文章中,我们将讨论如何从SqlServer中检索图片。并将学习以下几个方面的知识。

·如何设置图片的格式?

·如何使用BinaryWrite方法。

我们已经在Person表中存储了数据,那么我们就写些代码来从表中读取数据。

下面的代码检索了所有的值从Person表中。

从sqlserver中读取图片的代码。

PublicSubPage_Load(senderAsObject,eAsEventArgs)
DimmyConnectionAsNewSqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
DimmyCommandAsNewSqlCommand("Select*fromPerson",myConnection)
Try
myConnection.Open()
DimmyDataReaderasSqlDataReader
myDataReader=myCommand.ExecuteReader(CommandBehavior.CloseConnection)

DoWhile(myDataReader.Read())
Response.ContentType=myDataReader.Item("PersonImageType")
Response.BinaryWrite(myDataReader.Item("PersonImage"))
Loop

myConnection.Close()
Response.Write("Personinfosuccessfullyretrieved!")
CatchSQLexcAsSqlException
Response.Write("ReadFailed:"&SQLexc.ToString())
EndTry
EndSub

看看他是怎么工作的?

上面的例子很简单。我们所作的就是执行一个sql语句,再循环读取所有的记录(loopingthroughalltherecords).

在显示图片之前,我们先设置了图片的contentType,然后我们使用BinaryWrite方法把图片输出到浏览器。

源代码:

///retriving.aspx

<%@PageLanguage="vb"%>
<%@ImportNamespace="System.Data"%>
<%@ImportNamespace="System.Data.SqlClient"%>
<HTML>
<HEAD>
<title>RetrievingImagefromtheSqlServer</title>
<scriptrunat=server>
PublicSubPage_Load(senderAsObject,eAsEventArgs)
'CreateInstanceofConnectionandCommandObject
DimmyConnectionAsNewSqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
DimmyCommandAsNewSqlCommand("Select*fromPerson",myConnection)
Try
myConnection.Open()
DimmyDataReaderasSqlDataReader
myDataReader=myCommand.ExecuteReader(CommandBehavior.CloseConnection)

DoWhile(myDataReader.Read())
Response.ContentType=myDataReader.Item("PersonImageType")
Response.BinaryWrite(myDataReader.Item("PersonImage"))
Loop

myConnection.Close()
Response.Write("Personinfosuccessfullyretrieved!")
CatchSQLexcAsSqlException
Response.Write("ReadFailed:"&SQLexc.ToString())
EndTry
EndSub

</script>
</HEAD>
<bodystyle="font:10ptverdana">
</body>
</HTML>