کد HTML:
<%@ WebHandler Language="C#" Class="ImageFromDB" %>
using System;
using System.Web;
public class ImageFromDB : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string connectionString =
System.Configuration.ConfigurationManager.ConnectionStrings["My_DBConnectionString"].ConnectionString;
// Get the ID for this request.
string id = context.Request.QueryString["_id"];
if (id == null) throw new ApplicationException("Must specify ID.");
// Create a parameterized command for this record.
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connectionString);
string SQL = "SELECT _image FROM Table_image WHERE _id=@ID";
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(SQL, con);
cmd.Parameters.AddWithValue("@ID", id);
try
{
con.Open();
System.Data.SqlClient.SqlDataReader r =
cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);
if (r.Read())
{
int bufferSize = 100; // Size of the buffer.
byte[] bytes = new byte[bufferSize]; // The buffer.
long bytesRead; // The # of bytes read.
long readFrom = 0; // The starting index.
// Read the field 100 bytes at a time.
do
{
bytesRead = r.GetBytes(0, readFrom, bytes, 0, bufferSize);
context.Response.BinaryWrite(bytes);
readFrom += bufferSize;
} while (bytesRead == bufferSize);
}
r.Close();
}
finally
{
con.Close();
}
}
public bool IsReusable {
get {
return false;
}
}
}