我有一个问题开始让我感到沮丧。我使用 gridviews 创建了一个非常简单的博客。我被要求能够将图像上传到帖子中。我遇到的问题是,如果用户创建的帖子没有图片,则图像控件无论如何都会显示红色 x。我尝试了很多事情都没有成功。我正在使用自定义处理程序来获取帖子的图像。
图像处理程序.ashx
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboBlog"].ConnectionString);
public void ProcessRequest(HttpContext context)
{
try
{
string messageid = context.Request.QueryString["mid"];
conn.Open();
SqlCommand command = new SqlCommand("SELECT Image from BlogImages WHERE Image IS NOT NULL AND MessageID=" + messageid, conn);
SqlDataReader dr = command.ExecuteReader();
dr.Read()
context.Response.BinaryWrite((Byte[])dr[0]);
conn.Close();
context.Response.End();
}
catch (Exception ex)
{
return;
}
}
我确实有一个与 Post 表相关的图像表。如您所见,它使用 QueryString 并检索 MessageID 或 Posts id,然后显示图像。
这是我目前在 Posts.aspx 中用于图像控件的内容。
ASP
<asp:Image ID="postImage" runat="server" ImageUrl='<%# "ImageHandler.ashx?mid="+ Eval("MessageID") %>' Width="300px" Height="300px" GenerateEmptyAlternateText="True" />
我已经尝试过这里的解决方案以及这里的解决方案,但对我来说没有任何成功。我尝试使用 Visible 属性,只显示不是“空”但结果相同的图像。如果我还需要其他任何东西,请告诉我!
编辑:这就是我现在拥有的 ImageHandler.ashx
图像处理程序.ashx
// 1x1 transparent GIF
private readonly byte[] GifData =
{
0x47, 0x49, 0x46, 0x38, 0x39, 0x61,
0x01, 0x00, 0x01, 0x00, 0x80, 0xff,
0x00, 0xff, 0xff, 0xff, 0x00, 0x00,
0x00, 0x2c, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x01, 0x00, 0x00, 0x02,
0x02, 0x44, 0x01, 0x00, 0x3b
};
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboBlog"].ConnectionString);
public void ProcessRequest(HttpContext context)
{
try
{
string messageid = context.Request.QueryString["mid"];
conn.Open();
SqlCommand command = new SqlCommand("SELECT Image from BlogImages WHERE Image IS NOT NULL AND MessageID=" + messageid, conn);
SqlDataReader dr = command.ExecuteReader();
if (dr.Read())
{
context.Response.BinaryWrite((Byte[])dr[0]);
conn.Close();
context.Response.End();
}
else
{
context.Response.ContentType = "image/gif";
context.Response.Buffer = false;
context.Response.OutputStream.Write(GifData, 0, GifData.Length);
}
}
catch (Exception ex)
{
return;
}
}
我确实更新了 Win 给出的答案所提供的内容。唯一的问题是gridview确实有一个样式,每行都是白色和灰色之间交替的颜色。因此,如果没有图像并且在灰色行中,则会显示一个白色框。