简体   繁体   English

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

[英]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: 我应该把它放在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. 它说是ole对象。 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: 您应该像这样在Response上设置Content-Type Header:

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

Did you try returning that HTTP response message ? 您是否尝试返回该HTTP响应消息?

instead of void return that context of byte[] 代替void返回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 用于将图像保存在数据库中的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>

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) 用于从数据库中检索图像的Web表单(您的网页)

<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; 受保护的无效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"; //连接字符串connectionstring = @“ Provider = Microsoft.ACE.OLEDB.12.0;数据源= C:\\ Users \\ jeroen \\ Documents \\ Visual Studio 2010 \\ Projects \\ producten \\ producten \\ App_Data \\ Bimsports.accdb; Persist Security Info =真正”; OleDbConnection conn = new OleDbConnection(connectionstring); OleDbConnection conn =新的OleDbConnection(连接字符串);

    //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[] 然后我制作了一个类,用于查看您请求的数据库中的什么图像并将其放入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 关于图因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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