简体   繁体   中英

Retrieving image from database with handler

For a school project I have to make a webstore. I am trying to get the product image out of the database but I can't seem to make it to work I read somewhere on the internet that you're supposed to do that via a handler that's this:

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();
        }

and i was supposed to put this in the aspx:

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

I have no errors but the image won't show. Could anyone help me please?

edit:

by the way, the image is in an access database. it says ole object. is it still considered an image?

another edit:

if i put the query directly into access it gives me the column of the picture and not the picture itself...could that be the problem? if so how do i fix it?

You should set the Content-Type Header on the Response like this:

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

Did you try returning that HTTP response message ?

instead of void return that context of byte[]

i got it guys here turned out that i was missing a lot of code and that for some reason the saving a image via access itself didn't work. i instead made a page that loads it in there. for people with the same problem here is my code.

the webform to save the image in the database

<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>

the code behind that the webform for saving an image into your database

        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);
            }
        }


    }
}

the webform for retrieving the image from the database (your webpage)

<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>

the code behind the webpage

protected void Page_Load(object sender, EventArgs e) { int artikelnummer = 1; //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 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();
    }
}

then i made a class that looks at what image from the database you request and puts it in the 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);



        }
    }
}

and the handler is writing it on the page.

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;
        }
    }
}

it could probably be done easier and shorter, but hey, it works! thanks for all the input though

regards tuinj

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM