使用Asp.Net不从MySql数据库显示图像

时间:2016-01-02 11:30:09

标签: c# mysql asp.net

我想将图像添加到数据库中,并在成功添加后在网格视图中显示它。我编写了所有内容,但是当我添加详细信息并按保存时,图像不会显示在网页中。我附上了屏幕截图供参考。

Error image

以下是我使用的代码

.aspx代码

<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代码

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代码

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 个答案:

答案 0 :(得分:1)

您在SQL语句中遇到了在ASHX处理程序中使用的问题。首先,它产生一个不正确的SQL语句,其次它容易受SQL Injection attacks的影响。有关该问题的深入技术说明,请参阅OWASP Guidance

要修复代码,请先介绍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

}

还要将连接字符串从代码中移到web.config中。请参阅msdn文章Connection Strings and Configuration Files