vb.net使用ashx处理程序从SQL Server获取图像

时间:2013-08-30 15:36:51

标签: asp.net vb.net sql-server-2008-r2 ashx

我将员工图像存储在EMPPhotos数据类型的SQL Server 2008 R2上的image表中。我创建了一个通用的处理程序来从表中获取图像并将其发送到页面。这是行不通的。我已经测试了查询本身,我正在获取数据。

处理程序:

<%@ WebHandler Language="VB" Class="EmpImageHandler" %>

Imports System
Imports System.Web
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient

Public Class EmpImageHandler : Implements IHttpHandler

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        'context.Response.ContentType = "text/bmp"
        'context.Response.Write("Hello World")

        context.Response.ContentType = "text/bmp"
        Dim img As Image = GetImage(context.Request.QueryString("id"))
        img.Save(context.Response.OutputStream, ImageFormat.Bmp)
    End Sub

    Private Function GetImage(inID As Long) As Image
        Dim ms As MemoryStream = New MemoryStream

        Dim cnSTR As New clsConnections
        Dim cn As New SqlConnection(cnSTR.ConnectToDB("AgencyStaff"))
        Try
            cn.Open()
        Catch ex As Exception

        End Try
        Dim ssql As String = "Select BMPPhoto From EMPPhotos where empid = " & inID
        Dim CMD As SqlCommand = New SqlCommand(ssql, cn)
        Dim dr As SqlDataReader = CMD.ExecuteReader
        dr.Read()
        Dim img() As Byte = CType(dr("BMPPhoto"), Byte())
        ms = New MemoryStream(img, False)
        Return Image.FromStream(ms)
    End Function

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return True
        End Get
    End Property

End Class

提前感谢您的协助。

1 个答案:

答案 0 :(得分:2)

更改您的ContentType

自:

context.Response.ContentType = "text/bmp"

要:

context.Response.ContentType = "image/bmp"