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

ASP.NET
ASP.NET立即上手教程(13)
ASP.NET立即上手教程(14)
Repeater控件分页例子
从文本文件读取行信息
Asp.Net 2.0数据库基本操作方法学习
url传递中文的解决方案
如何实现无刷新的DropdownList联动效果
将非模态对话框显示为模态对话框
微软新版开发工具VS 2008 beta2功能定案
c#.net函数列表
.Net FW中无法正确显示中文问题
ASP.NET中的doPostBack脚本函数实例
教你在asp.net中动态变更CSS
一个功能齐全的DataGrid分页例子
在ASP.NET程序中创建唯一序号
asp.net 2.0中用GRIDVIEW插入新记录
ASP.Net中保护自定义的服务器控件
在ASP.NET中跨页面实现多选
转换DataSet到普通xml的新法
ASP.NET中用healthMonitor属性用法

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 66 ::
收藏到网摘: 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>