簡體   English   中英

從數據庫中檢索圖像文件並在Asp.Net中的網頁中顯示

[英]Retrieving image file from database and displaying in web page in Asp.Net

我正在嘗試在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>

任何幫助,將不勝感激。

創建一個用於圖像目的的頁面,說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"/>

您的SQL表中有4列稱為files

  1. FileId
  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();
            }

        }
    }
}

暫無
暫無

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

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