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

ASP.NET
asp.net css注释的影响
ASP.NET与数据库相关技巧
关于HtmlForm控件
三色交替的下拉列表框
精通ASP.NET中弹出窗口技术
ASP.NET Forums与现有系统整合方案示例
ASP.NET操作IIS中的虚拟目录
DataGrid与SQL Server 2000数据绑定
如何让Web应用程序在Client端实现导出报表功能
如何保证web app中的Send Email线程稳定性
关于用ASP.Net识别远程主机服务器种类
ASP.NET中上传下载文件
提高ASP.NET性能的方法
asp.net StreamReader 创建文件
asp.net如何生成图片验证码(简单)
一个.net 压缩位图至JPEG的代码
简单的SQL Server数据库数据读取与数据操作
获取网站的RSS聚合到自己的网页
.Net程序中整站通用的防SQL注入函数
asp.net生成缩略图及给原始图加水印的函数

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


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