有很多做你问的例子。这个答案分为两部分。首先,您需要(在您的 UI 页面上)确定存在哪些图像并根据查询结果显示\隐藏图像。接下来,您需要使用页面(或更恰当地说是 HttpHandler)在页面上显示图像。我在下面模拟了一个快速示例。我试图评论代码以帮助您通读它。
您的 ASPx 页面 (Html)
<form id="form1" runat="server">
<div>
<asp:Image ID="Image1" runat="server" />
<asp:Image ID="Image2" runat="server" />
<asp:Image ID="Image3" runat="server" />
<asp:Image ID="Image4" runat="server" />
<asp:Image ID="Image5" runat="server" />
</div>
</form>
这是一个包含 5 张图片的简单页面。您的页面会稍微复杂一些,但这仅用于演示目的。接下来我们将使用页面加载事件(或任何其他事件)从数据库中查找图像并隐藏未上传的图像。
ASPx 页面(代码)
protected void Page_Load(object sender, EventArgs e)
{
Session["memberreportid"] = 1; //TODO: Remove this
var query = "SELECT TOP 1 * FROM MemberReport where memberreportid=@p1";
//create the format string for each image. Note the last variable is {0} for additional formating
string imageSource = string.Format("/viewImage.ashx?memberreportid={0}&imageID={1}", Session["memberreportid"], "{0}");
//set our URL to our Image handler for each image
Image1.ImageUrl = string.Format(imageSource, 1);
Image2.ImageUrl = string.Format(imageSource, 2);
Image3.ImageUrl = string.Format(imageSource, 3);
Image4.ImageUrl = string.Format(imageSource, 4);
Image5.ImageUrl = string.Format(imageSource, 5);
//execute our command. Note we are using parameters in our SQL to circumvent SQL injection
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString))
{
var cmd = new SqlCommand(query, con);
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandTimeout = 3000;
cmd.Parameters.AddWithValue("@p1", Session["memberreportid"]);
con.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
//hide each image if the image is null or not a byte array (should always be a byte array)
if (reader["image1"] == null || !(reader["image1"] is byte[]))
Image1.Visible = false;
if (reader["image2"] == null || !(reader["image2"] is byte[]))
Image2.Visible = false;
if (reader["image3"] == null || !(reader["image3"] is byte[]))
Image3.Visible = false;
if (reader["image4"] == null || !(reader["image4"] is byte[]))
Image4.Visible = false;
if (reader["image5"] == null || !(reader["image5"] is byte[]))
Image5.Visible = false;
//we only want the first row so break (should never happen anyway)
break;
}
con.Close();
}
}
从上面可以看出,我们只是在做一个查询,根据找到的 ID 来查找上传了哪些图像。如果图像为空(或不是字节[]),则图像控件被隐藏。
最后一块是使用 HttpHandler(来自 New Item 列表的 GenericHandler)。HttpHandler 可能是您最好的选择,因为您不需要所有页面生成事件,并且可以直接挂钩到 HttpHandler 上下文。从这里您可以在 ASPx 页面(我个人的实现)中做几乎所有您想做的事情。注意默认情况下 HttpHandler 不能访问 Session 状态。
添加一个名为 viewImage.ashx 的新 GenericHandler(或任何您想要的)并添加以下代码。再次对此进行评论以帮助阅读。
viewImage.ashx 代码。
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Web;
namespace WebApplication1
{
/// <summary>
/// Summary description for viewImage
/// </summary>
public class viewImage : IHttpHandler
{
/// <summary>
/// process the request
/// </summary>
/// <param name="context">the current request handler</param>
public void ProcessRequest(HttpContext context)
{
///extract our params from the request
int memberID = 0, imageID = 0;
if (!int.TryParse(context.Request["memberreportid"], out memberID) ||
memberID <= 0 ||
!int.TryParse(context.Request["imageID"], out imageID) ||
imageID <= 0)
{
this.transmitError();
return;
}
//build our query
var query = string.Format("SELECT TOP 1 image{0} FROM MemberReport where memberreportid=@p1", imageID);
//execute the query
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString))
{
try
{
var cmd = new SqlCommand(query, con);
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandTimeout = 3000;
//set the member command type
cmd.Parameters.AddWithValue("@p1", memberID);
con.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
string psudoFileName = string.Format("memberReport_{0}_image{1}.png", memberID, imageID);
byte[] binary = reader[0] as byte[];
context.Response.ContentType = "image/png";
context.Response.AppendHeader("Content-Disposition", string.Format("filename=\"{0}\"", psudoFileName));
context.Response.AppendHeader("Content-Length", binary.Length.ToString());
context.Response.BinaryWrite(binary);
//todo: Implement your caching. we will use no caching
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
//we only want the first row so break (should never happen anyway)
break;
}
con.Close();
}
catch (Exception ex)
{
//TODO: Maybe some logging?
}
this.transmitError();
}
}
/// <summary>
/// transmits a non-image found
/// </summary>
void transmitError()
{
var context = HttpContext.Current;
if (context == null)
return;
//set the response type
context.Response.ContentType = "image/png";
//set as no-cache incase this image path works in the future.
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
//transmit the no-image found error
context.Response.TransmitFile(context.Server.MapPath("no-image.png"));
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
现在这应该是您在页面上显示图像并能够在上传图像时显示\隐藏图像所需的全部内容。
希望这可以帮助。