簡體   English   中英

如何使用c#從數據庫中檢索多個圖像

[英]how do I retrieve multiple images from the database using c#

我有一個9個圖像的數據庫,它不斷變化,所以我不能直接在html <img>標簽中設置src來顯示9個圖像,我必須從數據庫中選擇它們並相應地綁定它們。

我能夠使用Response.BinaryWrite()檢索和打印1個圖像,但不是全部9.我的byte[]只獲取db中的第一個圖像,

這是代碼,

            while (dr.Read())
            {
                Response.ContentType = "image/jpg";
                Response.BinaryWrite((byte[])(dr["fsImage"]));

            }

如何檢索所有9個圖像,以及如何將它們綁定到<asp:Image>標記或動態構造html <img>標記

我是新手,所以如果有愚蠢的錯誤,請放輕松我;)

提前致謝。

您無法讓網頁提供所有圖像的內容。

為了“動態”渲染圖像,您需要制作一個可以為您提供單個圖像的頁面。 此頁面將使用您上面的代碼。

然后選擇哪個圖像顯示頁面的URL會發生變化

http://youdomain/makeimage.aspx?imageid=1

http://youdomain/makeimage.aspx?imageid=2

然后,make image中的代碼將返回單個圖像。

注意 - 如果你制作網址,你會更開心

http://youdomain/makeimage.aspx?imageid=1&mytype=.jpg

因此,使圖像url在擴展名中結束。 一些瀏覽器(IE)作弊並查看字符串的結尾以查看期望的內容類型。 他們將使用上面的網址,但不是沒有試用.jpg。

此外,您需要實現某種形式的緩存,我們的性能將是一只狗(特別是如果您嘗試擴展)。

祝好運。

使用HttpHandler並調用Img標記

一個例子

<%@ WebHandler Language="C#" Class="Handler2" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;


public class Handler2 : IHttpHandler {


    public void ProcessRequest(HttpContext context)
    {

        if (context.Request.QueryString["pid"] != null)
        {
            string ID = context.Request.QueryString["pid"].ToString();

            if (dt.Rows.Count > 0)
            {
                int pid = Convert.ToInt32(ID);
                SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
                myConnection.Open();
                //int i = Convert.ToInt32(context.Request.QueryString["id"]);
                string sql = "Select BackGroundImage from Wall_BackgrndImg_Master where FK_Company_Master=@ImageId";
                SqlCommand cmd = new SqlCommand(sql, myConnection);
                cmd.Parameters.Add("@ImageId", SqlDbType.Int).Value = pid;
                cmd.Prepare();
                SqlDataReader dr = cmd.ExecuteReader();
                dr.Read();
                try
                {
                    context.Response.ContentType = "jpg";
                    context.Response.BinaryWrite((byte[])dr["BackGroundImage"]);
                    dr.Close();
                    myConnection.Close();
                }
                catch
                {

                }
            }
        }

    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

並打電話給

    <img src="~/handlor.ashx?pid=1">
<img src="~/handlor.ashx?pid=2">
<img src="~/handlor.ashx?pid=3">
<img src="~/handlor.ashx?pid=4">
<img src="~/handlor.ashx?pid=5">

暫無
暫無

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

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