如何从我的二进制代码显示我的页面上的图像

问题描述 投票:1回答:1

这是我第一次这样做。

所以我遵循了本教程:https://www.youtube.com/watch?v=YbiSrK4h1Kw

这就是我的ashx.cs文件中的代码-

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;

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

    public void ProcessRequest(HttpContext context)
    {
        string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\kfirm\Desktop\KEY_web_v1\KEY_web_v1\App_Data\Database1.mdf;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connectionString);
        //SqlConnection conn = new SqlConnection("data source=.\\sqlexpress; initial 
        catalog=SlideShow; integrated security=true");//ORIGINAL - "data source=.\\sqlexpress;             
        initial catalog=SlideShow; integrated security=true" //I think he's just making a dataset, I can edit later if it doesnt work or add this to the global.asax
        SqlCommand comm = new SqlCommand();
        comm.Connection = conn;

        comm.CommandText = "SELECT * FROM Portfolio WHERE id=5"; //MAKE A LOOP!!!!!!!!!!!!!!!!!!!!
        SqlDataAdapter da = new SqlDataAdapter(comm);
        DataTable dt = new DataTable();

        da.Fill(dt);

        byte[] image = (byte[])dt.Rows.[0][3]; //MAKE A LOOP!!!!!!!!!!!!!!!!!!!!

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

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

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

这是我的HTML代码:

<asp:Image ID="Image1" runat="server" ImageUrl="~/HandlerImage.ashx" Width="200" Height="200" />

这是我的数据库表:

CREATE TABLE [dbo].[Portfolio] (
[Image]       NVARCHAR (50)   NULL,
[Description] NVARCHAR (50)   NULL,
[ImageData]   VARBINARY (MAX) NULL,
[id]          INT             IDENTITY (1, 1) NOT NULL,
PRIMARY KEY CLUSTERED ([id] ASC)
);

这是我表的数据:

enter image description here

我有2个问题。一个是我收到此错误:enter image description here

第二个是没有图像显示:

enter image description here

c# sql handler ashx
1个回答
2
投票

删除行与[0]之间的点,这将修复语法错误。

您只能设置一次响应的ContentType,因此在此示例中,它将使用与PNG一起使用的最后一个值。

您已保存在数据库中的图像是JPG,因此可能会期望PNG在网站上正确显示。我建议您也将图像类型(JPG,PNG等)存储在数据库中。

© www.soinside.com 2019 - 2024. All rights reserved.