c# - 图像未使用 Asp.Net 从 MySql 数据库中显示

标签 c# mysql asp.net

我想把图片添加到数据库中,添加成功后显示在grid view中。我对所有内容进行了编码,但是当我添加详细信息并按保存时,网页中未显示图像。我已附上屏幕截图以供引用。

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;
        }
    }
}
}

最佳答案

您在 ASHX 处理程序中使用的 SQL 语句存在问题。首先,它会生成不正确的 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

关于c# - 图像未使用 Asp.Net 从 MySql 数据库中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34565378/

相关文章:

c# - 相同的 (?) C# 和 VB.NET LINQ 查询返回不同的结果

c# - 在文本中显示数字

mysql - java中的数据库连接程序

c# - 缺少 DLL 和引用的问题

javascript - 在 ASP.NET 中添加自定义属性。在 JQuery 中访问它

c# - 如何使用字段名称检索错误消息(服务器端)?

c# - 为什么在 lambda 中抛出异常是 C# 7 的一个特性?

php - 为什么mysql不存储 "#"字符后的数据?

mysql - mysql_real_escape-string 函数中的错误未转义特殊字符

asp.net - 当我按下浏览器的返回按钮时会发生什么?