62,075
社区成员
发帖
与我相关
我的任务
分享
<asp:ImageField HeaderText="照片" DataImageUrlField="员工号码" DataImageUrlFormatString="~/DisplayImage.ashx?EmpID={0}">
<ItemStyle HorizontalAlign="Center" />
<HeaderStyle Font-Bold="True" HorizontalAlign="Center" Width="150px" />
</asp:ImageField>
<%@ WebHandler Language="C#" Class="DisplayImage" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public class DisplayImage : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
// 取得员工号码。
string strEmpID = context.Request.QueryString["EmpID"];
strEmpID.Trim();
int intEmpID = Convert.ToInt32(strEmpID);
// 取得 web.config 中的数据库联机字符串设定来创建 SQL 联机对象。
using (SqlConnection cn = new SqlConnection(WebConfigurationManager.ConnectionStrings["chtNorthwind"].ConnectionString))
{
SqlCommand SQLCmd = cn.CreateCommand();
// 设定查询语句。
SQLCmd.CommandText = "SELECT [照片] FROM [dbo].[章立民研究室] WHERE [员工号码] = @ImageID";
// 使用 Parameters 集合此举会将输入视为常值,而不是可执行的程序代码
// 此外,可以强制执行类型和长度检查,当超出范围值时,会触发异常
// 因此使用 Parameters 集合可以避免发生 SQL Injection。
SQLCmd.Parameters.Add("@ImageID", SqlDbType.Int).Value = intEmpID;
// 开启数据库连接并将数据读入数据读取器中。
cn.Open();
using (SqlDataReader dr = SQLCmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (dr.Read())
{
// 改变 HTTP 文件头的输出格式,以便让浏览器知道所输出的文件格式是 JPEG 图文件。
context.Response.ContentType = "Image/JPEG";
context.Response.Clear();
context.Response.BufferOutput = true;
// 请注意,此处使用 SqlDataReader 的 GetSqlBytes 方法。
context.Response.BinaryWrite(dr.GetSqlBytes(0).Value);
}
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
资料不多,希望对楼主有帮助