vb.net using ashx handler to get image from SQL Server

不打扰是莪最后的温柔 提交于 2019-12-20 06:29:16

问题


I have employee images stored in my EMPPhotos table on SQL Server 2008 R2 in an image datatype. I created a generic handler to get the image from the table and send it to the page. It does not work. I have tested the query itself and I am getting data.

The handler:

<%@ 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

Thanks in advance for your assistance.


回答1:


Change your ContentType.

From:

context.Response.ContentType = "text/bmp"

To:

context.Response.ContentType = "image/bmp"


来源:https://stackoverflow.com/questions/18536690/vb-net-using-ashx-handler-to-get-image-from-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!