1

我正在尝试在 ASP.NET 网页中显示数据库中的图像。我正在使用通用处理程序 .aspx 和 .ashx。我试图显示它,但每次运行它时,它都会显示损坏的图像图标。

下面是我的.ashx代码:

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

namespace test
{
    /// <summary>
    /// Summary description for HandlerImage
    /// </summary>
    public class HandlerImage : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string connection = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
            using (var conn = new MySqlConnection(connection))
            {
                using (var comm = new MySqlCommand("SELECT FileId, [FileName], ContentType, Data FROM files WHERE FileId=16", conn))
                {
                    using (var da = new MySqlDataAdapter(comm))
                    {
                        var dt = new DataTable();
                        conn.Open();
                        da.Fill(dt);
                        conn.Close();
                        byte[] Data = (byte[])dt.Rows[0][3];

                       context.Response.ContentType = "image/jpeg";
                       context.Response.ContentType = "image/jpg";
                       context.Response.ContentType = "image/png";
                       context.Response.ContentType = "application/pdf";

                        context.Response.BinaryWrite(Data);
                        context.Response.Flush();
                    }

                }
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

下面是我的.aspx代码:

<div>
<asp:Image ID="Image1" runat="server" ImageUrl="HandlerImage.ashx?FileId=2" Width="200" Height="200"/>
</div>

任何帮助,将不胜感激。

4

2 回答 2

1

为图像目的创建一个页面GetMeImage.aspx,功能如下

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["ImageID"] != null)
    {
SqlConnection conn = new SqlConnection("DataSource=localhost; Database=varbinary; User ID=****; Password=****");
         SqlCommand comm = new SqlCommand();
         comm.Connection = conn;

         comm.CommandText = "select * from files where FileId=@id";
         comm.Parameters.AddWithValie("@id", Convert.ToInt32(Request.QueryString["ImageID"]);

         SqlDataAdapter da = new SqlDataAdapter(comm);
         DataTable dt = new DataTable();

         da.Fill(dt);



        if (dt != null)
        {
            Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = dt.Rows[0]["ContentType"].ToString();
            Response.AddHeader("content-disposition", "attachment;filename="
            + dt.Rows[0]["Name"].ToString());
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
    }
}

您要显示图像的页面上的以下代码:

<asp:image ID="Image1" runat="server" ImageUrl ="GetMeImage.aspx?ImageID=1"/>
于 2016-08-23T01:25:49.273 回答
0

您的 SQL 表中有 4 列,称为files

  1. 文件编号
  2. 文件名
  3. 内容类型
  4. 数据

但是在您的 C# 代码中,您选择第二列来获取图像:

byte[] Data = (byte[])dt.Rows[0][1];

它实际上应该是这样的:

byte[] Data = (byte[])dt.Rows[0][3];

除此之外,您应该更改用于检索图像的 ADO.NET 代码以将连接字符串存储在 web.config 文件中,并通过实现来使用适当的资源处理using{}

1.将连接字符串存储在web.config中:

<configuration>
  <connectionStrings>
    <add name="connection" connectionString="Put your SQL connection here"/>
  </connectionStrings>
    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>
</configuration>

2.像这样更改 HandlerImage.ashx:

public void ProcessRequest(HttpContext context)
{
    string connection = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
    using(var conn = new SqlConnection(connection))
    {
        using (var comm = new SqlCommand("SELECT FileId, [FileName], ContentType, Data FROM Files WHERE FileId=2",conn))
        {
            using(var da = new SqlDataAdapter(comm))
            {
                var dt = new DataTable();
                conn.Open();
                da.Fill(dt);
                conn.Close();
                byte[] Data = (byte[])dt.Rows[0][3];
                context.Response.BinaryWrite(Data);
                context.Response.Flush();
            }

        }
    }
}
于 2016-08-23T04:44:22.830 回答