使用处理程序从数据库中检索图像

时间:2014-05-21 13:54:17

标签: c# asp.net database

对于学校项目,我必须建立一个网上商店。我试图从数据库中获取产品图像,但我似乎无法使其工作 我在互联网上的某处读到你应该通过一个处理程序来做到这一点 就是这样:

public class afbeelding : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        //Connect
        string connectionstring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\jeroen\Documents\Visual Studio 2010\Projects\producten\producten\App_Data\Bimsports.accdb;Persist Security Info=True";
        OleDbConnection conn = new OleDbConnection(connectionstring);

        //execute
        int artikelnummer = 1;
        string sql = "SELECT foto FROM Artikel WHERE Artikelnummer =?";
        OleDbCommand cmd = new OleDbCommand(sql, conn);
        cmd.Parameters.AddWithValue("Artikelnummer", artikelnummer);
        //read
        try
        {
            conn.Open();
            OleDbDataReader reader = cmd.ExecuteReader();
            reader.Read();
            context.Response.BinaryWrite((byte[])reader["foto"]);
        }

        catch 
        {

        }
        finally
        {
            conn.Close();
        }

我应该把它放在aspx中:

<asp:Image ID="img_nikeshirt" runat="server" ImageUrl='<%# "afbeelding.ashx?ID=" + Eval("artikelnummer")%>'/>   

我没有错误,但图片不会显示。 有人可以帮我吗?

编辑:

顺便提一下,图像在访问数据库中。它说ole对象。 它仍然被认为是一个形象?

另一个编辑:

如果我直接将查询放入访问权限,它会给我图片的列而不是图片本身......这可能是问题吗?如果是这样我该如何解决?

3 个答案:

答案 0 :(得分:0)

您应该在响应中设置Content-Type标头,如下所示:

context.Response.ContentType = "image/png";
context.Response.BinaryWrite((byte[])reader["foto"]);
context.Response.Flush();

答案 1 :(得分:0)

您是否尝试返回该HTTP响应消息?

而不是void返回byte []

的上下文

答案 2 :(得分:0)

我知道这里的人们发现我错过了很多代码,而且出于某种原因,通过访问本身保存图像并不起作用。我做了一个页面,在那里加载它。 对于有同样问题的人来说,这是我的代码。

用于将图像保存在数据库中的webform

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
<asp:DropDownList ID="ddlartikel" runat="server" AutoPostBack="true" 
    onselectedindexchanged="ddlartikel_SelectedIndexChanged">
</asp:DropDownList>
<br />
<asp:Image ID="imgfoto" runat="server" />
<p>Verander Foto's</p>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="btnsave" runat="server" Text="Sla op in database" 
    onclick="btnsave_Click" />
</form>
</body>
</html>

用于将图像保存到数据库的webform背后的代码

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                //Connect
                string connectionstring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\jeroen\Documents\Visual Studio 2010\Projects\producten\producten\App_Data\Bimsports.accdb;Persist Security Info=True";
                OleDbConnection conn = new OleDbConnection(connectionstring);


                //Execute
                string sql = "SELECT Artikelnummer, Omschrijving FROM Artikel";
                OleDbCommand cmd = new OleDbCommand(sql, conn);
                //Read
                try
                {
                    conn.Open();
                    OleDbDataReader reader = cmd.ExecuteReader();
                    ddlartikel.DataSource = reader;
                    ddlartikel.DataValueField = "artikelnummer";
                    ddlartikel.DataTextField = "omschrijving";
                    ddlartikel.DataBind();
                }
                    finally{conn.Close();}
                FetchPicture();
            }
        }

        protected void ddlartikel_SelectedIndexChanged(object sender, EventArgs e)
        {
            FetchPicture();
        }
        private void FetchPicture()
        {
            if (ddlartikel.SelectedIndex > -1)
            {
                int artikelnummer = Convert.ToInt32(ddlartikel.SelectedValue);
                string sUrl = string.Format("~/afbeelding.ashx?artikelnummer={0}", artikelnummer);
                imgfoto.ImageUrl = sUrl;
            }
        }

        protected void btnsave_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                byte[] MyData = FileUpload1.FileBytes;

                int artikelnummer = Convert.ToInt32(ddlartikel.SelectedValue);
                CBlob.SavePicture(artikelnummer, MyData);
            }
        }


    }
}

用于从数据库(您的网页)检索图像的网络表单

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        Merk:
        <asp:Label ID="lbl_merk" runat="server"></asp:Label>
        <br />
        Maat:
        <asp:Label ID="lbl_maat" runat="server"></asp:Label>
        <br />
        Omschrijving:
        <asp:Label ID="lbl_omschrijving" runat="server"></asp:Label>
        <br />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        Kleur:
        <asp:Label ID="lbl_kleur" runat="server"></asp:Label>
        <br />
        Prijs:
        <asp:Label ID="lbl_prijs" runat="server"></asp:Label>
        <br />
        BTW:
        <asp:Label ID="lbl_btw" runat="server"></asp:Label>
        <br />
        Categorie: 
        <asp:Label ID="lbl_categorie" runat="server"></asp:Label>

        <br />

        <br />
        <asp:Image ID="img_nikeshirt" runat="server" ImageUrl='<%# "afbeelding.ashx?ID=" + Eval("artikelnummer")%>'/>    
    </div>

    </form>
</body>
</html>

网页背后的代码

protected void Page_Load(object sender,EventArgs e)     {         int artikelnummer = 1;         //连接         string connectionstring = @&#34; Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\ Users \ jeroen \ Documents \ Visual Studio 2010 \ Projects \ producten \ producten \ App_Data \ Bimsports.accdb; Persist Security Info =真&#34 ;;         OleDbConnection conn = new OleDbConnection(connectionstring);

    //Execute
    string sql = "SELECT Merk, Maat, Omschrijving, Kleur, Prijs, BTW, Categorie.Categorie FROM Artikel INNER JOIN Categorie ON Artikel.Categorie = Categorie.Categorienummer WHERE Artikelnummer =?";
    OleDbCommand cmd = new OleDbCommand(sql, conn);
    cmd.Parameters.AddWithValue("Artikelnummer", artikelnummer);
    //Read
    try
    {
        conn.Open();
        OleDbDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            lbl_merk.Text = reader["Merk"].ToString();
            lbl_maat.Text = reader["Maat"].ToString();
            lbl_omschrijving.Text = reader["Omschrijving"].ToString();
            lbl_kleur.Text = reader["Kleur"].ToString();
            lbl_prijs.Text = reader["Prijs"].ToString();
            lbl_btw.Text = reader["BTW"].ToString();
            lbl_categorie.Text = reader["Categorie"].ToString();
        }
        string sUrl = string.Format("~/afbeelding.ashx?artikelnummer={0}", artikelnummer);
        img_nikeshirt.ImageUrl = sUrl;

    }
    catch
    {

    }
    finally
    {
        conn.Close();
    }
}

然后我创建了一个类,它查看您请求的数据库中的图像,并将其放在byte []

       public static byte[] getpicture(int artikelnummer)
        {
            string connectionstring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\jeroen\Documents\Visual Studio 2010\Projects\producten\producten\App_Data\Bimsports.accdb;Persist Security Info=True";
            OleDbConnection conn = new OleDbConnection(connectionstring);
            //Execute
            string sql = "SELECT foto FROM Artikel WHERE Artikelnummer =?";
            OleDbCommand cmd = new OleDbCommand(sql, conn);
            cmd.Parameters.AddWithValue("Artikelnummer", artikelnummer);
            try
            {
                byte[] photodata = null;
                conn.Open();
                OleDbDataReader reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {
                    reader.Read();
                    if (!reader.IsDBNull(0))
                    {
                        photodata = new byte[Convert.ToInt32((reader.GetBytes(0, 0, null, 0, Int32.MaxValue)))];
                        long bytesreceived = reader.GetBytes(0, 0, photodata, 0, photodata.Length);
                    }
                }
                return photodata;
            }
            catch (Exception ex)
            {
            }
            finally
            {
                conn.Close();
            }
            return null;
        }
        public static bool SavePicture(int artikelnummer, byte[] photodata)
        {
            int rowupdated = 0;

            string connectionstring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\jeroen\Documents\Visual Studio 2010\Projects\producten\producten\App_Data\Bimsports.accdb;Persist Security Info=True";
            OleDbConnection conn = new OleDbConnection(connectionstring);

            string sql = "UPDATE Artikel SET foto=? WHERE artikelnummer=?";
            OleDbCommand cmd = new OleDbCommand(sql, conn);


            conn.Open();

            OleDbParameter param = new OleDbParameter("@foto", OleDbType.VarBinary, photodata.Length);
            param.Value = photodata;
            cmd.Parameters.Add(param);
            cmd.Parameters.AddWithValue("Artikelnummer", artikelnummer);
            rowupdated = (int)cmd.ExecuteNonQuery();

            return (rowupdated>0);



        }
    }
}

并且处理程序正在页面上写它。

public class afbeelding : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        int artikelnummer = 0;

        if (context.Request.QueryString["artikelnummer"] != null)
        {
            artikelnummer = int.Parse(context.Request.QueryString["artikelnummer"]);
        }
        if (artikelnummer != 0)
        {
            byte[] bytes = CBlob.getpicture(artikelnummer);

            if (bytes != null)
            {
                context.Response.ContentType = "image/jpeg";
                context.Response.OutputStream.Write(bytes, 0, bytes.Length);
            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

它可能更容易和更短,但嘿,它的工作原理! 感谢所有输入

关于tuinj