62,241
社区成员




<%@ WebHandler Language="VB" Class="Handler" %>
Imports System
Imports System.Web
imports System.IO
imports System.Data
imports System.Data.SqlClient
Imports System.Configuration
Public Class Handler : Implements IHttpHandler
Private ConStr As String = ConfigurationManager.ConnectionStrings("ConnectionStore").ConnectionString
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'get images type
dim ImageType as String = context.Request.QueryString("type").ToString()
dim ID as Integer = ctype(context.Request.QueryString("id"),Integer)
'set output type
context.Response.ContentType = ImageType
context.Response.Cache.SetCacheability(HttpCacheability.Public)
context.Response.BufferOutput = False
dim Streams as Stream = nothing
'get picture stream from tbBannerAdv
Streams = GetPicture(ID)
'set buffer
dim BufferSize as Int32 = 1024*16
dim Bytes as Byte() = new Byte(BufferSize) {}
dim Count as Integer = Streams.Read(Bytes,0,BufferSize)
while Count>0
context.Response.OutputStream.Write(Bytes,0,Count)
Count = Streams.Read(Bytes,0,BufferSize)
end while
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return True
End Get
End Property
'check input is null or empty
Private Function IsNotEmpty(ByVal text As String) As Boolean
Dim Result As Boolean
If String.IsNullOrEmpty(text) Then
Result = False
Else
Result = True
End If
Return Result
End Function
private function GetPicture(id as Integer) as Stream
dim QuerySql as String = "SELECT image FROM tbBannerAdv WHERE id=@ID"
if IsNotEmpty(id) then
using Con as SqlConnection = new SqlConnection(ConStr)
using Cmd as SqlCommand = new SqlCommand(QuerySql,Con)
try
Cmd.Parameters.AddWithValue("@ID",id)
Con.Open()
'get picture
dim Results as Object = cmd.ExecuteScalar()
'return picture stream
return new MemoryStream(ctype(Results,Byte()))
Catch ex As Exception
Con.Dispose()
end try
end using
end using
End If
End Function
End Class
<img src='Handler.ashx?id=<%# Eval("id") %>&type=<%# Eval("ImageMimetype")%>' alt="N/A"
width="160px" height="80px" border="0" />
protected void Page_Load(object sender, EventArgs e)
{
string id = Request["id"].ToString();
string connstr = "server=.;integrated security=sspi;database=Test";
SqlConnection connection = new SqlConnection(connstr);
SqlCommand cmd = new SqlCommand("select ImageData from MyPictures where Id="+id, connection);
connection.Open();
byte[] imageData = (byte[])cmd.ExecuteScalar();
connection.Close();
Response.OutputStream.Write(imageData, 0,imageData.Length);
}