How to get a specific image from a database?

I have an image control on an aspx page such as

<asp:Image ID="Image1" runat="server" Height="64px" Width="64px" ImageUrl='<%# "SideImageHandler.ashx?ID=" + Eval("ID")%>'/> 

And my image handler code is as follows

  public void ProcessRequest(HttpContext context) { SqlConnection con = new SqlConnection(); con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["GalleryConnectionString"].ConnectionString; // Create SQL Command Utility.ImageID = 2; SqlCommand cmd = new SqlCommand(); cmd.CommandText = "SELECT IMAGE FROM Icon WHERE (ID ="+ Utility.ImageID+")"; cmd.CommandType = System.Data.CommandType.Text; cmd.Connection = con; SqlParameter ImageID = new SqlParameter("@ID", System.Data.SqlDbType.Int); ImageID.Value = context.Request.QueryString["ID"]; cmd.Parameters.Add(ImageID); con.Open(); SqlDataReader dReader = cmd.ExecuteReader(); dReader.Read(); context.Response.BinaryWrite((byte[])dReader["IMAGE"]); dReader.Close(); con.Close(); } 

But it does not show me the image. What is happening to him?

In addition, I have a download button, when the user clicks on it, the image will be downloaded. I'm new, don’t know what code I put on the download button click event? I ask you to notify me in advance

+1
c # sql-server image
source share
1 answer

This is just a sample. Use :

  <asp:image id="Image1" imageUrl="SideImageHandler.ashx?ID=<someId>"/> 

add this to config:

 <httpHandlers> <add verb="*" path="img/*" type="SideImageHandler"/> </httpHandlers> 

and in the handler:

  public void ProcessRequest (HttpContext context) { int ID; if (context.Request.QueryString["ID"] != null) ID= Convert.ToInt32(context.Request.QueryString["ID"]); else throw new ArgumentException("No parameter specified"); byte[] imageData= ;//get the image data from the database using the employeeId Querystring Response.ContentType = "image/jpeg"; Response.BinaryWrite(imageData); } 
+3
source share

All Articles