Click here to Skip to main content
15,885,909 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi every one. i am working on c# program that retrieve image from database. i used http general handler to accomplish this operation. when i run my application and put check points everything is okay and work correctly and no error but image does not display on webpage. i am working on windows server 2008 , vs2008 .

the application work as following:
i had textbox1 and button. the user inter id of sql table row and click button1 to display image in image1 control.


---------------the Default.aspx code :

var ids = (from g in dh.SessionQuestions
where g.idMain == Convert.ToInt32(TextBox1.Text)
select g).ToList().FirstOrDefault();
Label1.Text = Convert.ToString(ids.Question);
int c = Convert.ToInt32(ids.idMain);

Image1.ImageUrl = "~/handler1.ashx?idMain" + c;

-----------------------and handler1.ashx code:


public class handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
SqlDataReader rdr;

SqlConnection conn = new SqlConnection("Data Source=WIN-MFKUGM21HBL\\SQLEXPRESS;Initial Catalog=OnLineTest;Integrated Security=True");

try
{
var pic_query = "SELECT Image1 FROM SessionQuestion WHERE idMain=" + context.Request.QueryString["idMain"].ToString() + "";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = (pic_query);
cmd.Connection = conn;
conn.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{

context.Response.ContentType = "image/jpeg";

if (rdr["Image1"] != DBNull.Value)
{
context.Response.BinaryWrite((Byte[])rdr["Image1"]);
// context.Response.Write((Byte[])rdr["Image1"]);
}

}

if (rdr != null)
rdr.Close();
}
catch { }
finally
{
if (conn != null)
conn.Close();
}
}

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

1 solution

Start by checking the code you used to save the image: that's normally the problem, particularly when you don't always use parameterised queries, as you show you don't in the example code above. Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

This may help: Why do I get a "Parameter is not valid." exception when I read an image from my database?[^]
 
Share this answer
 
Comments
Badour alsamaraie 27-Jan-15 6:34am    
thanks,,, i am appreciate your solution. i tried fro 3 days and can not the answer. thanks again
OriginalGriff 27-Jan-15 6:56am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900