简体   繁体   English

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

[英]Image is not displaying from the MySql Database using Asp.Net

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. 我已附上屏幕截图以供参考。

错误图片

Here is the code that I used 这是我使用的代码

.aspx code .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 code .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 code 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;
        }
    }
}
}

You have an issue in your SQL statement that you use in the ASHX handler. 您在ASHX处理程序中使用的SQL语句中存在问题。 First of all it produces an incorrect SQL statement and secondly it is vulnerable for SQL Injection attacks . 首先,它会生成错误的SQL语句,其次,它很容易受到SQL Injection攻击的攻击 See the OWASP Guidance for in depth technical explanation of the issue. 有关该问题的详细技术说明,请参阅OWASP指南

To fix your code introduce MySqlParameters : 要修复您的代码,请引入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. 还将连接字符串从代码中移至web.config。 See the msdn article Connection Strings and Configuration Files 请参阅msdn文章“ 连接字符串和配置文件”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM