asp.net

位置:IT落伍者 >> asp.net >> 浏览文章

在ASP.net 中从sqlserver检索(retrieve)图片


发布日期:2019年12月29日
 
在ASP.net 中从sqlserver检索(retrieve)图片
介绍

这篇文章是我写的如何把图片存入sqlServer中的后续我建议你在读这篇文章之前先看看那篇

和存储图片相比读取图片就要简单多了输出一副图片我们要做的就是使用Response对象的BinaryWrite方法同时设置图片的格式在这篇文章中我们将讨论如何从SqlServer中检索图片并将学习以下几个方面的知识

1.如何设置图片的格式?

2.如何使用BinaryWrite方法

我们已经在Person表中存储了数据那么我们就写些代码来从表中读取数据下面的代码检索了所有的值从Person表中

从sqlserver中读取图片的代码

Public Sub Page_Load(sender As Object e As EventArgs)

Dim myConnection As New SqlConnection(ConfigurationSettingsAppSettings(ConnectionString))

Dim myCommand As New SqlCommand(Select * from Person myConnection)

Try

myConnectionOpen()

Dim myDataReader as SqlDataReader

myDataReader = myCommandExecuteReader(CommandBehaviorCloseConnection)

Do While (myDataReaderRead())

ResponseContentType = myDataReaderItem(PersonImageType)

ResponseBinaryWrite(myDataReaderItem(PersonImage))

Loop

myConnectionClose()

ResponseWrite(Person info successfully retrieved!)

Catch SQLexc As SqlException

ResponseWrite(Read Failed : & SQLexcToString())

End Try

End Sub

看看他是怎么工作的?

上面的例子很简单我们所作的就是执行一个sql语句再循环读取所有的记录(looping through all the records)在显示图片之前我们先设置了图片的contentType然后我们使用BinaryWrite方法把图片输出到浏览器

源代码

/// retrivingaspx

<%@ Page Language=VB %>

<%@ Import Namespace=SystemData %>

<%@ Import Namespace=SystemDataSqlClient %>

<HTML>

<HEAD>

<title>Retrieving Image from the SQL Server</title>

<script runat=server>

Public Sub Page_Load(sender As Object e As EventArgs)

Create Instance of Connection and Command Object

Dim myConnection As New SqlConnection(ConfigurationSettingsAppSettings(ConnectionString))

Dim myCommand As New SqlCommand(Select * from Person myConnection)

Try

myConnectionOpen()

Dim myDataReader as SqlDataReader

myDataReader = myCommandExecuteReader(CommandBehaviorCloseConnection)

Do While (myDataReaderRead())

ResponseContentType = myDataReaderItem(PersonImageType)

ResponseBinaryWrite(myDataReaderItem(PersonImage))

Loop

myConnectionClose()

ResponseWrite(Person info successfully retrieved!)

Catch SQLexc As SqlException

ResponseWrite(Read Failed : & SQLexcToString())

End Try

End Sub

</script>

</HEAD>

<body style=font: pt verdana>

</body>

</HTML>

上一篇:如何在ASP.Net 中把图片存入数据库

下一篇:ASP.NET入门教程2.6.3 通过浏览器编辑站点配置[1]