Karthik Malla
Karthik Malla

Reputation: 5820

displaying an image in ASP.NET

How to an image which is retrieved from MYSQL database.

To display a text in textbox we use textbox.TEXT --> We use .TEXT to display text

Likewise how to display an Image retrieved from MYSQL database??

Image1.[___] = dr[0].[_____];

What to be filled in the above blanks??...

I used blob to store image.

Upvotes: 0

Views: 424

Answers (2)

Mike Brind
Mike Brind

Reputation: 30110

Add a Generic Handler to your Web Forms application and in the ProcessRequest method, you need to query the database for the relevant file/binary data. You would pick the right image via a querystring, usually. The following code shows how you can query the database and return the binary data:

using (DbConnection conn = new DbConnection(connect))
{
  if (context.Request.QueryString["id"] != null)
  {
    DbCommand cmd = new DbCommand(qry, conn);
    cmd.Parameters.AddWithValue("", context.Request.QueryString["id"]);
    conn.Open();
    using (DbDataReader rdr = cmd.ExecuteReader())
    {
      if (rdr.HasRows)
      {
        rdr.Read();
        context.Response.AddHeader("content-disposition", "attachment; filename=" + rdr["FileName"]);
        context.Response.ContentType = rdr["MimeType"].ToString();
        context.Response.BinaryWrite((byte[])rdr["Blob"]);
      }
    }
  }
}

You need to change the DbConnection, DbCommand and DbDataReader to the type that your provider likes (Odbc or MySql) and then point the ImageUrl property of your Image control to the HttpHandler:

Image1.ImageUrl = "MyHandler.ashx?id=" + whatever the image id is.

Upvotes: 1

Kelsey
Kelsey

Reputation: 47766

You can do it by creating a controller to serve up your image like and then in your view you can just add the call inline:

<img src='<%= Url.Action( "GetImage", "Image", new { id = yourImageIdHere } ) %>' /> 

public class ImageController
{
    public ActionResult GetImage(int id)
    {
        var image = GetTheRawBinaryImageFromTheDB();
        return File(image, "image/jpg" );
    }
 } 

Upvotes: 2

Related Questions