1

I am trying to display an image from the database in an ASP.NET web page. I'm using a generic handler .aspx and .ashx. I have tried to display it but everytime I run it, it displays the broken image icon.

Below is my .ashx code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Configuration;
using MySql.Data.MySqlClient;

namespace test
{
    /// <summary>
    /// Summary description for HandlerImage
    /// </summary>
    public class HandlerImage : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string connection = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
            using (var conn = new MySqlConnection(connection))
            {
                using (var comm = new MySqlCommand("SELECT FileId, [FileName], ContentType, Data FROM files WHERE FileId=16", conn))
                {
                    using (var da = new MySqlDataAdapter(comm))
                    {
                        var dt = new DataTable();
                        conn.Open();
                        da.Fill(dt);
                        conn.Close();
                        byte[] Data = (byte[])dt.Rows[0][3];

                       context.Response.ContentType = "image/jpeg";
                       context.Response.ContentType = "image/jpg";
                       context.Response.ContentType = "image/png";
                       context.Response.ContentType = "application/pdf";

                        context.Response.BinaryWrite(Data);
                        context.Response.Flush();
                    }

                }
            }

        }

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

Below is my .aspx code:

<div>
<asp:Image ID="Image1" runat="server" ImageUrl="HandlerImage.ashx?FileId=2" Width="200" Height="200"/>
</div>

Any help would be appreciated.

2
  • Have you registered your .ashx in web.config? You may have to do it in two places (one for integrated pipeline, one for classic). Commented Aug 23, 2016 at 1:07
  • Instructions Commented Aug 24, 2016 at 16:23

2 Answers 2

1

Create a page for image purpose say GetMeImage.aspx with function as below

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["ImageID"] != null)
    {
SqlConnection conn = new SqlConnection("DataSource=localhost; Database=varbinary; User ID=****; Password=****");
         SqlCommand comm = new SqlCommand();
         comm.Connection = conn;

         comm.CommandText = "select * from files where FileId=@id";
         comm.Parameters.AddWithValie("@id", Convert.ToInt32(Request.QueryString["ImageID"]);

         SqlDataAdapter da = new SqlDataAdapter(comm);
         DataTable dt = new DataTable();

         da.Fill(dt);



        if (dt != null)
        {
            Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = dt.Rows[0]["ContentType"].ToString();
            Response.AddHeader("content-disposition", "attachment;filename="
            + dt.Rows[0]["Name"].ToString());
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
    }
}

Below code on the page where you want to display image:

<asp:image ID="Image1" runat="server" ImageUrl ="GetMeImage.aspx?ImageID=1"/>
Sign up to request clarification or add additional context in comments.

2 Comments

Where did you get the ImageID? In my database, there are only FileId, FileName, ContentType and Data(image file).
ImageID is QueryString parameter passed from <asp:image ID="Image1" ...
0

You have 4 columns in your SQL table called files:

  1. FileId
  2. FileName
  3. ContentType
  4. Data

But in your C# code you are selecting the second column to get the image:

byte[] Data = (byte[])dt.Rows[0][1];

It should actually be like this:

byte[] Data = (byte[])dt.Rows[0][3];

In addition to this you shoud change your ADO.NET code for retrieving the image to store the connection string in the web.config file and use proper resource disposal by implementing using{}

1.Store the connection string in web.config:

<configuration>
  <connectionStrings>
    <add name="connection" connectionString="Put your SQL connection here"/>
  </connectionStrings>
    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>
</configuration>

2.Change the HandlerImage.ashx like this:

public void ProcessRequest(HttpContext context)
{
    string connection = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
    using(var conn = new SqlConnection(connection))
    {
        using (var comm = new SqlCommand("SELECT FileId, [FileName], ContentType, Data FROM Files WHERE FileId=2",conn))
        {
            using(var da = new SqlDataAdapter(comm))
            {
                var dt = new DataTable();
                conn.Open();
                da.Fill(dt);
                conn.Close();
                byte[] Data = (byte[])dt.Rows[0][3];
                context.Response.BinaryWrite(Data);
                context.Response.Flush();
            }

        }
    }
}

5 Comments

I copied everything but the image still does not show up. Is it because of my ImageUrl at <asp:Image ID="Image1" runat="server" ImageUrl="HandlerImage.ashx?FileId=2"/>?
No your image URL is fine and working on my side.Place a break point on string connection does it get hit when you access the page?Where does the code fail?
Yes I did but it's for the codes that are irrelevant to the HandlerImage. Can you email me your code? It would really help.
I've posted all my code in the answer you need to add a break point to public void ProcessRequest(HttpContext context) and tell me if it's being hit or not.
Define "being hit"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.