the image is inserted into the db successfully , but cant retrieve it

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kavinhuh
    New Member
    • Feb 2012
    • 13

    the image is inserted into the db successfully , but cant retrieve it

    Hello ladies and gentlemen of the forum. I bear grevious news. I am able to execute the following code which saves an image file to my database without error. I am confident that the image is saved as expected. Yet to my horror I find then when I try to display my image in a gridview it does not appear in the same way Santa Clause does. I am all a tither! Alas and alack! Oh, who will save me?
    httphandler (generic handler)>>
    Code:
    public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
    SqlConnection con = new SqlConnection();
    con.ConnectionString = "Data Source=HOME-PC\\SQLEXPRESS;Initial Catalog=imagek;Integrated Security=True";
    
    con.Open();
    SqlCommand command = new SqlCommand("SELECT * from image ", con);
    SqlDataReader dr = command.ExecuteReader();
    dr.Read();
    context.Response.BinaryWrite((Byte[])dr[0]);
    //context.Response.ContentType = "text/plain";
    //context.Response.Write("Hello World");
    con.Close();
    context.Response.End();
    }
    
    public bool IsReusable {
    get {
    return false;
    }
    }
    
    }
    default page>>
    i have an uploader control , the image is inserted into the db successfully , but cant retrieve it>>
    Code:
    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.Data.SqlClient;
    using System.Windows.Forms;
    //using System.Web.
    
    public partial class _Default : System.Web.UI.Page
    {
    
    //con.ConnectionString =SqlConnection con = new SqlConnection();
    
    public SqlConnection con = new SqlConnection();
    protected void Page_Load(object sender, EventArgs e)
    {
    con.ConnectionString = "Data Source=HOME-PC\\SQLEXPRESS;Initial Catalog=imagek;Integrated Security=True";
    
    
    
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
    if (FileUpload1.HasFile)
    {
    
    con.Open();
    byte[] img = new byte[FileUpload1.PostedFile.ContentLength];
    HttpPostedFile myimg = FileUpload1.PostedFile;
    myimg.InputStream.Read(img, 0, FileUpload1.PostedFile.ContentLength);
    
    SqlCommand cmd = new SqlCommand("insert into image values(22,'"+ img +"')",con);
    
    cmd.ExecuteNonQuery();
    
    con.Close();
    }
    }
    protected void Button2_Click(object sender, EventArgs e)
    { DataSet ds = new DataSet();
    con.Open();
    SqlCommand command = new SqlCommand("SELECT id from image ", con);
    // SqlCommand command = new SqlCommand("SELECT imagename,ImageID from [Image]", connection);
    SqlDataAdapter daimages = new SqlDataAdapter(command);
    DataTable dt = new DataTable();
    daimages.Fill(dt);
    GridView1.DataSource = dt;
    GridView1.DataBind();
    GridView1.Attributes.Add("bordercolor", "black");
    
    
    
    
    
    
    
    }
    
    }
    Last edited by jhardman; Feb 18 '12, 12:29 AM. Reason: Moved to correct forum (accidentally posted in the asp classic forum). Added code tags (this is in our posting guidelines, please read these before posting again). Corrected English (I refuse to help
  • Newface
    New Member
    • Feb 2012
    • 16

    #2
    Please include a webhandler to display your image in gridview,otherw ise i think it is not possible,if possible then do intimate me.for now include a templatefield in your gridview columns like below
    Code:
    <asp:TemplateField>
                                <ItemTemplate>
                                    <img src="~/ShowImage.ashx?FacultyID=<%# Eval(FacultyID) %>" runat="server" width="100" height="50"/>
                                </ItemTemplate>
                            </asp:TemplateField>
    in load of your aspx.cs
    Code:
    pID = Request.QueryString["FacultyID"].ToString();
    cmd.Parameters.Add(new SqlParameter("@FacultyID", pID));
                        DataTable dt = new DataTable();
                        da.Fill(dt);
                        profileGridView.DataSource = dt;
                        profileGridView.DataBind();
    and the page where you are redirecting from,in aspx.cs,include ;
    Code:
     string stext=cmdFacultyID.Text.Trim().ToString();
                Response.Redirect(ResolveUrl("~/FacultyMaster/Faculty Profile.aspx?FacultyID="+stext));

    Comment

    • PsychoCoder
      Recognized Expert Contributor
      • Jul 2010
      • 465

      #3
      Take a look at this, it's in VB.NET but converting it to C# shouldn't be that difficult

      Comment

      • Newface
        New Member
        • Feb 2012
        • 16

        #4
        Dear PsychoCoder,i am a beginner in this technology and forum so please please excuse my minor mistakes and negligence.

        Comment

        • kavinhuh
          New Member
          • Feb 2012
          • 13

          #5
          dear newface: even after including the web handler , i am retrieving the whole table in gridview,but the image is not shown as shown in attachment , am i missing some code ?
          Attached Files

          Comment

          • Newface
            New Member
            • Feb 2012
            • 16

            #6
            please post your updated code so that could help you further if possible.
            Last edited by Newface; Feb 22 '12, 05:54 PM. Reason: updated was inserted

            Comment

            • kavinhuh
              New Member
              • Feb 2012
              • 13

              #7
              here i have included the files of my project , please help me
              DEFAULT.ASPX.CS
              Code:
              using System;
              using System.Collections;
              using System.Configuration;
              using System.Data;
              using System.Linq;
              using System.Web;
              using System.Web.Security;
              using System.Web.UI;
              using System.Web.UI.HtmlControls;
              using System.Web.UI.WebControls;
              using System.Web.UI.WebControls.WebParts;
              using System.IO;
              using System.Xml.Linq;
              using System.Data.SqlClient;
              using System.Windows.Forms;
              
              //using System.Web.
              
              public partial class _Default : System.Web.UI.Page
              {
                  
                  //con.ConnectionString =SqlConnection con = new SqlConnection();
              
                public SqlConnection con = new SqlConnection();
                  protected void Page_Load(object sender, EventArgs e)
                  {
                      con.ConnectionString = "Data Source=HOME-PC\\SQLEXPRESS;Initial Catalog=imagek;Integrated Security=True";
                        
                     //if(!Roles.RoleExists("admin"))
                     //{}
              
                  }
                  protected void Button1_Click(object sender, EventArgs e)
                  {
                      if (FileUpload1.HasFile)
                      {
                           
                          con.Open();
                          byte[] img = new byte[FileUpload1.PostedFile.ContentLength];
                          HttpPostedFile myimg = FileUpload1.PostedFile;
                          myimg.InputStream.Read(img, 0, FileUpload1.PostedFile.ContentLength);
              
                          SqlCommand cmd = new SqlCommand("insert into image values(22,'"+ img +"')",con);
                       
                          cmd.ExecuteNonQuery();
              
                          con.Close();
                      }
                  }
                  protected void Button2_Click(object sender, EventArgs e)
                  { DataSet ds = new DataSet();
                  con.Open();
                  SqlCommand command = new SqlCommand("SELECT id from image ", con);
                //  SqlCommand command = new SqlCommand("SELECT imagename,ImageID from [Image]", connection);
                  SqlDataAdapter daimages = new SqlDataAdapter(command);
                  DataTable dt = new DataTable();
                  daimages.Fill(dt);
                  GridView1.DataSource = dt;
                  GridView1.DataBind();
                  GridView1.Attributes.Add("bordercolor", "black");
                      
                       
                         
                  Image img = new Image();
                 // ImageMap1.DataSource = ds;
                    
              
              
                  }
                  
              }
              WEB.CONFIG
              Code:
              <?xml version="1.0"?>
              <!-- 
                  Note: As an alternative to hand editing this file you can use the 
                  web admin tool to configure settings for your application. Use
                  the Website->Asp.Net Configuration option in Visual Studio.
                  A full list of settings and comments can be found in 
                  machine.config.comments usually located in 
                  \Windows\Microsoft.Net\Framework\v2.x\Config 
              -->
              
              <configuration>
              	<configSections>
              		<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
              			<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
              				<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
              				<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
              					<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
              					<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
              					<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
              					<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
              				</sectionGroup>
              			</sectionGroup>
              		</sectionGroup>
              	</configSections>
              	<appSettings/>
              	<connectionStrings>
                <add name="imagekConnectionString" connectionString="Data Source=home-pc\sqlexpress;Initial Catalog=imagek;Integrated Security=True"
                 providerName="System.Data.SqlClient" />
               </connectionStrings>
                  
                <!--</roleManager>-->
              	<system.web>
              		<!-- 
                          Set compilation debug="true" to insert debugging 
                          symbols into the compiled page. Because this 
                          affects performance, set this value to true only 
                          during development.
                      -->
              		<compilation debug="true">
              			<assemblies>
              				<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
              				<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
              				<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
              				<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
              				<add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies>
              		</compilation>
              		<!--
                          The <authentication> section enables configuration 
                          of the security authentication mode used by 
                          ASP.NET to identify an incoming user. 
                      -->
              		<authentication mode="Windows"/>
              		<!--
                          The <customErrors> section enables configuration 
                          of what to do if/when an unhandled error occurs 
                          during the execution of a request. Specifically, 
                          it enables developers to configure html error pages 
                          to be displayed in place of a error stack trace.
              
                      <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
                          <error statusCode="403" redirect="NoAccess.htm" />
                          <error statusCode="404" redirect="FileNotFound.htm" />
                      </customErrors>
                      -->
              		<pages>
              			<controls>
              				<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
              				<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
              			</controls>
              		</pages>
              		<httpHandlers>
              			<remove verb="*" path="*.asmx"/>
              			<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
              			<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
              			<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
              		</httpHandlers>
              		<httpModules>
              			<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
              		</httpModules>
              	</system.web>
              	<system.codedom>
              		<compilers>
              			<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
              				<providerOption name="CompilerVersion" value="v3.5"/>
              				<providerOption name="WarnAsError" value="false"/>
              			</compiler>
              			<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
              				<providerOption name="CompilerVersion" value="v3.5"/>
              				<providerOption name="OptionInfer" value="true"/>
              				<providerOption name="WarnAsError" value="false"/>
              			</compiler>
              		</compilers>
              	</system.codedom>
              	<!-- 
                      The system.webServer section is required for running ASP.NET AJAX under Internet
                      Information Services 7.0.  It is not necessary for previous version of IIS.
                  -->
              	<system.webServer>
              		<validation validateIntegratedModeConfiguration="false"/>
              		<modules>
              			<remove name="ScriptModule"/>
              			<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
              		</modules>
              		<handlers>
              			<remove name="WebServiceHandlerFactory-Integrated"/>
              			<remove name="ScriptHandlerFactory"/>
              			<remove name="ScriptHandlerFactoryAppServices"/>
              			<remove name="ScriptResource"/>
              			<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
              			<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
              			<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
              		</handlers>
              	</system.webServer>
              	<runtime>
              		<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
              			<dependentAssembly>
              				<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
              				<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
              			</dependentAssembly>
              			<dependentAssembly>
              				<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
              				<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
              			</dependentAssembly>
              		</assemblyBinding>
              	</runtime>
              </configuration>
              GENERIC HANDLER
              Code:
              <%@ WebHandler Language="C#" Class="Handler" %>
              
              using System;
              using System.Web;
              using System.Data.SqlClient;
              
              public class Handler : IHttpHandler {
                  
                  public void ProcessRequest (HttpContext context) {
                      
                      string imageid = context.Request.QueryString["ImID"];
                      SqlConnection con = new SqlConnection();
                      con.ConnectionString = "Data Source=HOME-PC\\SQLEXPRESS;Initial Catalog=imagek;Integrated Security=True";
                      
                      con.Open();
                      SqlCommand command = new SqlCommand("SELECT imagefile from image ", con);
                      SqlDataReader dr = command.ExecuteReader();
                      dr.Read();
                      context.Response.BinaryWrite((Byte[])dr[0]);
                      //context.Response.ContentType = "text/plain";
                      //context.Response.Write("Hello World");
                      con.Close();
                      context.Response.End();
                  }
               
                  public bool IsReusable {
                      get {
                          return true ;
                      }
                  }
              
              }
              [B]DEFAULT ASPX[/B]
              <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
              
              <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
              
              <html xmlns="http://www.w3.org/1999/xhtml">
              <head runat="server">
                  <title>Untitled Page</title>
              </head>
              <body>
                  <form id="form1" runat="server">
                  <div>
                  
                  </div>
                  <asp:FileUpload ID="FileUpload1" runat="server" />
                  <p>
                      <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
                      <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Button" />
                  </p>
                  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
                  <Columns>
                  <asp:BoundField HeaderText = "Image Name" DataField="id" />
              <asp:TemplateField HeaderText="Image">
              <ItemTemplate>
              <asp:Image ID="Image1" runat="server" ImageUrl='<%# "Handler.ashx?ImID="+ Eval("id") %>' Height="150px" Width="150px"/>
              </ItemTemplate>
              </asp:TemplateField>
              </Columns>
                  </asp:GridView>
                 
                  </form>
              </body>
              </html>
              Last edited by Frinavale; Feb 24 '12, 03:25 PM. Reason: Added code tags. In the future Please enclose code in code tags.

              Comment

              • Newface
                New Member
                • Feb 2012
                • 16

                #8
                just minor edit like
                in place of
                //SqlDataReader dr = command.Execute Reader();
                //dr.Read();
                //context.Respons e.BinaryWrite(( Byte[])dr[0]);
                //context.Respons e.ContentType = "text/plain";
                //context.Respons e.Write("Hello World");
                Code:
                byte[] imgContent=(byte[])command.ExecuteScalar();
                context.Response.ContentType = "image/jpeg"; 
                context.Response.OutputStream.Write(imgContent,0,imgContent.Length);
                in your Generic Handler,and in your default aspx,in place of
                //<asp:TemplateFi eld HeaderText="Ima ge">
                //<ItemTemplate >
                //<asp:Image ID="Image1" runat="server" ImageUrl='<%# "Handler.ashx?I mID="+ Eval("id") %>' Height="150px" Width="150px"/>
                //</ItemTemplate>
                //</asp:TemplateFie ld>

                add
                Code:
                <asp:TemplateField>
                                                                    <ItemTemplate>
                 <img runat="server" src="Handler.ashx?ImID=<%# Eval(ImID) %>" Height="150" Width="150"/>                                                       
                
                                                                    </ItemTemplate>
                                                                </asp:TemplateField>
                try doing this and it will get resolved.
                Last edited by Newface; Feb 24 '12, 07:58 PM. Reason: parameter in Write method was added

                Comment

                • Newface
                  New Member
                  • Feb 2012
                  • 16

                  #9
                  is this working for you?,anyway, i have prepared one test file for you as can see below:
                  Code:
                  //in Handler.ashx
                  public void ProcessRequest(HttpContext context)
                      {
                          string Name = context.Request.QueryString.Get("ProfileName");
                          SqlConnection con = clsConnection.GetConnection();
                          SqlCommand cmd = new SqlCommand("GetDatah");
                          SqlDataReader dr = null;
                          cmd.CommandType = CommandType.StoredProcedure;
                          cmd.Parameters.Add(new SqlParameter("@profileName", Name));
                          cmd.Connection = con;
                          con.Open();
                          dr =  cmd.ExecuteReader();
                          while (dr.Read())
                          {
                              context.Response.BinaryWrite((byte[])dr[0]);
                              //byte[] imgData = (byte[])cmd.ExecuteScalar();
                              //context.Response.ContentType = "image/bmp";
                              //context.Response.OutputStream.Write(imgData, 0, imgData.Length);
                              con.Close();
                              context.Response.End();
                          }
                      }
                  Code:
                  //in aspx.cs
                      protected void cmdShowProfile_Click(object sender, EventArgs e)
                      {
                          con = clsConnection.GetConnection();
                          cmd = new SqlCommand("GetDataAll");
                          dt = new DataTable();
                          da = new SqlDataAdapter();
                          cmd.CommandType = CommandType.StoredProcedure;
                          profileName = txtName.Text.Trim();
                          //cmd.Parameters.Add(new SqlParameter("@profileName", profileName));
                          cmd.Connection = con;
                          da.SelectCommand = cmd;
                          da.Fill(dt);
                          if (dt.Rows.Count > 0)
                          {
                              GrdvPicture.DataSource = dt;
                              GrdvPicture.DataBind();
                          }
                          else
                              GrdvPicture.EmptyDataText = "No record found";
                          
                      //cmdShowProfile.PostBackUrl = "Default.aspx?ProfileName='"+profileName+"'" ;
                          //Response.Redirect("~/Default.aspx?ProfileName="+profileName, true);
                      }
                      protected void GrdvPicture_RowDataBound(object sender, GridViewRowEventArgs e)
                      {
                          if (e.Row.RowType == DataControlRowType.DataRow)
                          {
                              string ProfileName=Convert.ToString(DataBinder.Eval(e.Row.DataItem,"ProfileName"));
                              Image img = (Image)e.Row.FindControl("ProfileImage");
                              
                          }
                      }
                  Code:
                  //in .aspx
                  <asp:GridView ID="GrdvPicture" runat="server" AutoGenerateColumns="False" 
                                                              DataKeyNames="ProfileName" OnRowDataBound="GrdvPicture_RowDataBound">
                                                              <Columns>
                                                                  <asp:BoundField DataField="ProfileName" HeaderText="Name" />
                                                                  <asp:TemplateField HeaderText="Image">
                                                                      <ItemTemplate>
                                                                          <asp:Image ID="ProfileImage" runat="server" ImageUrl='<%#"Handler.ashx?ProfileName="+Eval("ProfileName") %>' Height="50px" Width="50px"  />
                                                                       
                                                                      </ItemTemplate>
                                                                  </asp:TemplateField>
                                                              </Columns>
                                                          </asp:GridView>

                  Comment

                  Working...