Database management systems often provide support for large binary objects. Of course, binary object fields do not have to store images. They can also store media files, long text files, or other binary content.
The following uses loading Employee photos from a database as an example to demonstrate an HTTP processing program:
Public class dbimagehandler: ihttphandler
{
Public void processrequest (httpcontext CTX)
{
// Obtain the employee ID from the query string
Int id =-1;
Bool reaust = int32.tryparse (CTX. Request. querystring ["ID"], out ID );
// If the employee ID cannot be obtained from the query string, the processing of the HTTP request is immediately interrupted.
If (! Result)
CTX. response. End ();
// Database connection string
String connstring = "...";
String plain text = "select photo from employees where employeeid = @ ID ";
// Read the photo field from the database to obtain employee photos.
Byte [] IMG = NULL;
Sqlconnection conn = new sqlconnection (connstring );
Using (conn)
{
Sqlcommand cmd = new sqlcommand (plain text, Conn );
Cmd. Parameters. addwithvalue ("@ ID", ID );
Conn. open ();
IMG = (byte []) cmd. executescalar ();
Conn. Close ();
}
If (IMG! = NULL)
{
// Set the contexttype field in the HTTP header to indicate that the data in the body is of the image type.
CTX. response. contexttype = "image/JPEG ";
// Output the image to the browser
CTX. response. binarywrite (IMG );
}
}
Public bool isreusable
{
Get {return true ;}
}
}
This Code makes a few assumptions: first, the field named photo Stores image data in JPEG format. Second, the image is obtained from a fixed database table through a predefined connection string. Finally, the URL that calls the processing program must contain a query string parameter named ID.
Note: This code tries to convert the type before using the value of the query parameter ID. By verifying whether the ID parameter contains data-type data, it can significantly reduce the risk of external attacks.
The binarywrite method of the httpresponse object can write the byte array to the output stream.
Register in Web. config
The HTTP handler must be registered in the web. config file and bound to a public endpoint:
<add verb="*" path="dbimage.axd" type="Core35.Components.dbImageHandler,Core35Lib" />
Use
Enter a URL similar to the following in your browser: http: // localhost: 57023/core35/dbimage. axd? Id = 1. This URL indicates querying the staff photos with employee ID 1 in the database.
We can also bind similar URLs to the image control on the Web Control for dynamic image access.