簡體   English   中英

使用Asp.Net無法從MySql數據庫顯示圖像

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

我想將圖像添加到數據庫中,並在成功添加后將其顯示在網格視圖中。 我對所有內容進行了編碼,但是當我添加詳細信息並按保存時,該圖像不會顯示在網頁中。 我已附上屏幕截圖以供參考。

錯誤圖片

這是我使用的代碼

.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攻擊的攻擊 有關該問題的詳細技術說明,請參閱OWASP指南

要修復您的代碼,請引入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文章“ 連接字符串和配置文件”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM