图片未从数据库显示

时间:2019-07-06 16:46:14

标签: sql asp.net webforms

我正在将DataList与SqlDataSource一起使用,其中所有内容都已预先设置。图片成功存储到数据库中(图像以字节存储到数据库中),在TestQuery中,该图像是可见的,并且所有标题和描述都显示在网页上,只是该图像没有显示。

Picture Here

<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource" RepeatColumns="3" RepeatDirection="Horizontal">
    <ItemTemplate>
        <asp:Image ID="Image1" runat="server" Height="200px" ImageUrl='<%# Eval("image") %>' Width="200px" />
        <br />
        <asp:Label ID="Label1" runat="server" Text='<%# Eval("title") %>'></asp:Label>
        &nbsp;<br />
        <asp:Label ID="Label2" runat="server" Text='<%# Eval("desc") %>'></asp:Label>
        <br />
    </ItemTemplate>
</asp:DataList>


<asp:SqlDataSource ID="SqlDataSource" 
                   runat="server" 
                   ConnectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SnorDB.mdf;
                   Integrated Security=True;
                   MultipleActiveResultSets=True;
                   Application Name="EntityFramework" 
                   ProviderName="System.Data.SqlClient" 
                   SelectCommand="SELECT [image], [title], [desc] FROM [Art]">
</asp:SqlDataSource>

1 个答案:

答案 0 :(得分:1)

创建通用处理程序

public void ProcessRequest(HttpContext context)
{
    string imageid = context.Request.QueryString["id"].ToString();
    SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SnorDB"].ConnectionString);
    connection.Open();
    SqlCommand command = new SqlCommand("select image from [Art] where imageid=" + imageid, connection);
    SqlDataReader dr = command.ExecuteReader();
    dr.Read();
    context.Response.BinaryWrite((Byte[])dr[0]);
    connection.Close();
    context.Response.End();

}

public bool IsReusable
{
    get
    {
        return false;
    }
}

在显示网页上

ImageUrl='<%# "ImageHandler.ashx?id="+ Eval("imageid")

通过将ID传递给处理程序。

参考:Here