从数据库中检索图像文件并在Asp.Net的网页中显示

时间:2016-08-23 01:02:11

标签: c# asp.net database imagehandler

我正在尝试在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>

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

创建一个图像用途的页面,如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"/>

答案 1 :(得分:0)

SQL表中有4列名为files

  1. FILEID
  2. 文件名
  3. 的ContentType
  4. 数据
  5. 但是在您的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();
                }
    
            }
        }
    }