65.9K
CodeProject 正在变化。 阅读更多。
Home

如何读取BLOB并显示它们

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.88/5 (15投票s)

2006年3月24日

2分钟阅读

viewsIcon

116651

downloadIcon

1409

从数据库读取 BLOB(图像)并在 ASP.NET 应用程序中显示它们。

blobreadasp.gif

引言

最近,我开发了一个电子商务网站,一个手机购物商城,页面及其内容是在客户选择他们喜欢的手机时动态创建的。手机的图像和手机供应商的徽标都存储在数据库中作为 BLOB。我想读取这个 BLOB 并在客户请求时显示它。我创建了一个示例应用程序,用于读取 BLOB 并显示它,以演示这一点。

我使用 SQL Server 安装时创建的 pubs 数据库作为本示例。我将从 pub_info 表中填充的出版物 ID 填充到下拉列表中,当选择完成后,将显示相应的徽标。

使用代码

创建一个单独的 aspx 文件来保存图像。一个 aspx 文件来保存图像?你在开玩笑吗?等等,看看发生了什么。在 aspx 页面的代码隐藏文件中创建一个方法来读取 BLOB 值。 CreateImage(string id) 是读取 BLOB 的方法。 string id 参数获取用户从下拉列表中选择的图像 ID。要读取 BLOB 值,请使用 SqlCommand 类的 ExecuteScalar() 方法。 ExecuteScalar() 返回一个 object,因此我们应该将其转换为并存储在 byte 数组中,如下所示。

byte[] _buf = (byte[]) _cmd.ExecuteScalar();

然后,将其流式传输回 HTTP 响应。完整的代码如下所示

void  CreateImage(string id)
{
    // Connectoin string is taken from web.config file.
    SqlConnection _con = new SqlConnection(
      System.Configuration.ConfigurationSettings.AppSettings["DB"]);
        
    try
    {
        _con.Open();
        SqlCommand _cmd = _con.CreateCommand();
        _cmd.CommandText = "select logo from" + 
                           " pub_info where pub_id='" + 
                           id + "'";
        byte[] _buf = (byte[])_cmd.ExecuteScalar();
        
        // This is optional
        Response.ContentType = "image/gif";
        
        //stream it back in the HTTP response
        Response.BinaryWrite(_buf);
                
                
    }
    catch
    {}
    finally
    {
        _con.Close();
                
    }
}

Page_Load() 中,调用 CreateImage()

private void Page_Load(object sender, System.EventArgs e)
{
    if(!IsPostBack)
    {
        CreateImage(Request["id"]);
    }
}

该页面使用查询字符串检索图像 ID。现在,我要显示图像。为了显示图像,请在您想要的位置使用 HtmlServerControl。像这样设置其 src 属性。

<img src='<%# "imgs.aspx?id=" + drpIds.SelectedValue %>'>

要评估这个神奇的数据绑定公式,我们应该调用

Page.DataBind();

在下拉列表的 SelectedIndexChanged 事件中。

就这样。运行应用程序并享受它吧。

© . All rights reserved.