在formview中显示图像

时间:2013-05-06 12:00:56

标签: c# asp.net .net

我有一个问题,我的图片来自客户签名的数据库。

如何使用Formview

<% #Eval() %>上绑定该签名
          <tr>
              <td>
                    Display Signature :
              </td>
              <td>
                    <%#Eval("SignatureImage") %>
              </td>
          </tr>

1 个答案:

答案 0 :(得分:1)

您可以使用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-对象