首页 > 解决方案 > 如何从我的二进制代码在我的页面上显示图像

问题描述

这是我第一次这样做。

所以我跟着这个教程: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)
);

这就是我的表格数据:

在此处输入图像描述

我有2个问题。一个是我收到此错误: 在此处输入图像描述

第二个是没有图像显示:

在此处输入图像描述

标签: c#sqlhandlerashx

解决方案


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

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

您保存在数据库中的图像是 JPG,因此它可能无法在网站上正确显示,因为它需要 PNG。我建议您也将图像类型(JPG、PNG 等)存储在数据库中。


推荐阅读