Muhammad Qurashi
Muhammad Qurashi

Reputation: 61

I can read image from database but I don't know how I can view image in asp.net page?

I have the following code to read an image from a database:

cn = new SqlConnection(@"Data Source=ADMIN-PC;Initial Catalog=imagedata;Integrated Security=True");

cmd = new SqlCommand("select *  from image where imgid=1", cn);
cn.Open();
SqlDataReader dr;

try
{
    dr = cmd.ExecuteReader();

    if (dr.Read())
    {
        byte[] imgarr = (byte[])dr["img"];
        ms = new MemoryStream(imgarr);
        ms.Seek(0, SeekOrigin.Begin);
   }
}
catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}
finally
{
   cn.Close();
}

How can I update this to show the image on an ASP.Net page?

Upvotes: 0

Views: 293

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

In ASP.Net, this code belongs in a separate resource (file/page) from the page where you want to show the image. Normally I use a handler (*.ashx) for this, but you can use a normal page (*.aspx) if you really want to (hint: the handler is faster and easier). Move your existing code to the ProcessRequest() method (handler) or Page_Load() method (Page), and alter the code so that instead of a memory stream it writes to the Response stream. You will also need to set the appropriate content type header.

Once that is done, update the page where you want to show the image. Use a normal <img element or an <asp:Image control (either will work) and set the src attribute to use the resource we created in the previous paragraph. You'll likely need to make the resource smart enough the check something like the session, query string, or a cookie, for data telling it the key of the database record to pull for the image. If you used a query string, make sure to set that as part of the src attribute at this time as well.

Upvotes: 7

Related Questions