1

I want to add the image to the database and display it in the grid view when it is added successfully. I coded everything, but when I add the details and press save the image is not displayed in the web page. I've attached screen shot for reference.

Error image

Here is the code that I used

.aspx code

<form id="form1" runat="server">
<div>
    <table>  
        <tr>  
            <td colspan="2">  
                <h2>Employee Details</h2>  
            </td>  
        </tr>  
        <tr>  
            <td>ID</td>  
            <td><asp:TextBox ID="txtID" runat="server" Width="211px"></asp:TextBox></td>  
        </tr>  
        <tr>  
            <td>Name</td>  
            <td><asp:TextBox ID="txtName" runat="server" Width="211px"></asp:TextBox></td>  
        </tr>  
        <tr>  
            <td>BloodGroup</td>  
            <td><asp:TextBox ID="txtBloodGroup" runat="server" Width="211px"></asp:TextBox></td>  
        </tr>  
        <tr>  
            <td>Emergency Contact No.</td>  
            <td><asp:TextBox ID="txtContactNo" runat="server" Width="211px"></asp:TextBox></td>  
        </tr>  
        <tr>  
            <td>Photo:</td>  
            <td><asp:FileUpload ID="fileuploadEmpImage" runat="server" Width="180px" /></td>  
        </tr>  
        <tr>  
            <td colspan="2"><asp:Button ID="btnSubmit" runat="server" Text="Save" OnClick="btnSubmit_Click" /></td>  
        </tr>  
    </table>  
</div>  
<div>  
    <asp:GridView ID="grdEmployee" runat="server" AutoGenerateColumns="false">  
        <Columns>  
         <asp:BoundField HeaderText="Name" DataField="Name" />  
          <asp:BoundField HeaderText="Blood Group" DataField="BloodGroup" />  
          <asp:BoundField HeaderText="Phone No" DataField="PhoneNo" />  
            <asp:BoundField HeaderText="Image" DataField="Image" Visible="false" />  
            <asp:TemplateField HeaderText="Image">  
                <ItemTemplate>  
                    <asp:Image ID="Image1" runat="server" ImageUrl='<%# "EmployeeImageHandler.ashx?Id="+ Eval("Id") %>'  
                        Height="150px" Width="150px" />  
                </ItemTemplate>  
            </asp:TemplateField>  
        </Columns>  
    </asp:GridView>      
</div>
</form>

.aspx.cs code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;

namespace Image_upload
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindGridData();
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {   
            if (fileuploadEmpImage.HasFile)
            {
                int length = fileuploadEmpImage.PostedFile.ContentLength;
                byte[] imgbyte = new byte[length];
                HttpPostedFile img = fileuploadEmpImage.PostedFile;
                img.InputStream.Read(imgbyte, 0, length);
                int id = Convert.ToInt32(txtID.Text);
                string name = txtName.Text;
                string bloodGroup = txtBloodGroup.Text;
                string phoneNo = txtContactNo.Text;

                String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
                MySqlConnection connection = new MySqlConnection(myConnection);
                connection.Open();
                MySqlCommand cmd = new MySqlCommand("INSERT INTO database.employee (Id,Name,BloodGroup,PhoneNo,ImageI)" + "values('"+ txtID.Text +"', '"+ txtName.Text +"', '"+ txtBloodGroup.Text +"', '"+ txtContactNo.Text +"', '"+ fileuploadEmpImage.FileBytes +"')", connection);
                int count = cmd.ExecuteNonQuery();
                connection.Close();
                if (count == 1)
                {
                    txtID.Text = string.Empty;
                    txtName.Text = string.Empty;
                    txtBloodGroup.Text = string.Empty;
                    txtContactNo.Text = string.Empty;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('Record added successfully')", true);
                    BindGridData();
                }
            }
        }

        private void BindGridData()
        {
            String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
            MySqlConnection connection = new MySqlConnection(myConnection);
            MySqlCommand command = new MySqlCommand("SELECT Id,Name,BloodGroup,PhoneNo,ImageI from database.employee", connection);
            MySqlDataAdapter daimages = new MySqlDataAdapter(command);
            DataTable dt = new DataTable();
            daimages.Fill(dt);
            grdEmployee.DataSource = dt;
            grdEmployee.DataBind();  
        }
    }
}

handler.ashx.cs code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;


namespace Image_upload
{

public class Employeeimage_handler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string imageid = context.Request.QueryString["Id"];
        String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
        MySqlConnection connection = new MySqlConnection(myConnection);
        connection.Open();
        MySqlCommand command = new MySqlCommand("select ImageI from database.employee order by ID" + imageid, connection);
        MySqlDataReader dr = command.ExecuteReader();
        dr.Read();
        context.Response.BinaryWrite((Byte[])dr[0]);
        connection.Close();
        context.Response.End(); 
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
}
1
  • Off-topic: I highly recommend you look into MVC and Entity Framework. This way to do code is about 10 years old. Commented Jan 2, 2016 at 11:47

1 Answer 1

1

You have an issue in your SQL statement that you use in the ASHX handler. First of all it produces an incorrect SQL statement and secondly it is vulnerable for SQL Injection attacks. See the OWASP Guidance for in depth technical explanation of the issue.

To fix your code introduce MySqlParameters:

public void ProcessRequest(HttpContext context)
{
    string imageid = context.Request.QueryString["Id"];
    var connection = new MySqlConnection(
                        ConfigurationManager.ConnectionString["database"]);
    connection.Open();
    // remove the order by and add a where with a parameter placeholder
    var command = new MySqlCommand(
                     "select ImageI from database.employee where id = @id",
                     connection);
    // setup parameter and add to command
    command.Parameters.AddWithValue("@id", imageid);
    // execute
    MySqlDataReader dr = command.ExecuteReader();

    // rest of your code

}

Also move the connection string out of your code to the web.config. See the msdn article Connection Strings and Configuration Files

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.