Monday, March 12, 2012

ms sql image + vb.net

Hi,

could anyone help me how to get the images from ms sql database with asp.net (visual basic)?

I have a field in the database with datatype image, and there are a couple of images in this table.

Now I am wondering how to get this images and view them on my .aspx page?

Thank you.I've have solved it.

<%@. Page Language="vb" debug="true" %>
<%@. Import Namespace="System.Data" %>
<%@. Import Namespace="System.Data.SqlClient" %>
<script runat="server">

Dim u As String

Sub Page_load
u = Request.QueryString("u")
getImage(u)
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<script runat=server
Public Sub getImage(ByVal u)

' Create Instance of Connection and Command Object

Dim myConnection As New SqlConnection("Server=localhost;uid=xx;pwd=xx;database=xx")

Dim myCommand As New SqlCommand("Select avatarImage from yaf_user where Name = @.u", myConnection)
myCommand.Parameters.AddWithValue("@.u", u)

Try

myConnection.Open()

Dim myDataReader As SqlDataReader

myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)

Do While (myDataReader.Read())

'Response.ContentType = myDataReader.Item("avatar")
Response.ContentType = "image/gif"
Response.BinaryWrite(myDataReader.Item("avatarImage"))

Loop

myConnection.Close()

Response.Write("Person info successfully retrieved!")

Catch SQLexc As SqlException

Response.Write("Read Failed : " & SQLexc.ToString())

End Try

End Sub

</script>
</body>
</html

No comments:

Post a Comment