您可以使用 httphandler 检索二进制图像,然后将其绑定到具有 src 属性的图像控制。检查这个完整的示例代码:
ImgHandler.ashx:
<%@ WebHandler Language="C#" Class="ImgHandler" %>
using System;
using System.Web;
using System.Data.Sql;
using System.Data.SqlClient;
public class ImgHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
byte[] buffer = null;
string querySqlStr = "";
if (context.Request.QueryString["ImageID"] != null)
{
querySqlStr="select * from testImageTable where ID="+context.Request.QueryString["ImageID"];
}
else
{
querySqlStr="select * from testImageTable";
}
SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TestDataBaseConnectionString"].ToString());
SqlCommand command = new SqlCommand(querySqlStr, connection);
SqlDataReader reader = null;
try
{
connection.Open();
reader = command.ExecuteReader();
//get the extension name of image
while (reader.Read())
{
string name = reader["imageName"].ToString();
int endIndex = name.LastIndexOf('.');
string extensionName = name.Remove(0, endIndex + 1);
buffer = (byte[])reader["imageContent"];
context.Response.Clear();
context.Response.ContentType = "image/" + extensionName;
context.Response.BinaryWrite(buffer);
context.Response.Flush();
context.Response.Close();
}
reader.Close();
}
finally
{
connection.Close();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
.aspx 文件:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<img src="ImgHandler.ashx?ImageID=1" alt="" />
<img src="ImgHandler.ashx?ImageID=2" alt="" />
<img src="ImgHandler.ashx?ImageID=3" alt="" />
<img src="ImgHandler.ashx?ImageID=4" alt="" />
</div>
</form>
</body>
</html>
如果您没有 HTTP 处理程序,请查看以下参考资料:
http://msdn.microsoft.com/en-us/library/bb398986.aspx
https://stackoverflow.com/questions/1096122/how-do-i-use-an-ashx-handler-with-an-aspimage-object _