c# - 如何从我的二进制代码在我的页面上显示图像
问题描述
这是我第一次这样做。
所以我跟着这个教程: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)
);
这就是我的表格数据:
第二个是没有图像显示:
解决方案
删除 Rows 和 [0] 之间的点,这将修复语法错误。
您只能设置一次响应的 ContentType,因此在此示例中,它将使用与 PNG 一起使用的最后一个值。
您保存在数据库中的图像是 JPG,因此它可能无法在网站上正确显示,因为它需要 PNG。我建议您也将图像类型(JPG、PNG 等)存储在数据库中。
推荐阅读
- vue.js - 在Vue中实时保持时间和时差
- excel - Excel 索引间接关闭工作簿
- r - `[.default`(data, subgroups[[1]]) 中的错误:无效的下标类型“符号”
- html -
将html表格提取到R中,但在多页html中跳过具有三行/行的某一列中的特定元素( ) - mongoose - 异步等待中的错误处理
- java - 批处理未运行,JDBC
- android - 检查 LinearLayout 是否有 Clipped Child
- bash - awk 不写入文件
- specman - Specman e:如何打印指向结构的指针?
- javascript - 如何使用 Express.js 从所有对象中获取数据?