Reputation: 17
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.
Upvotes: 1
Views: 1420
Reputation: 17049
You have 4 columns in your SQL table called files
:
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();
}
}
}
}
Upvotes: 0
Reputation: 3800
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"/>
Upvotes: 1