您的位置:首页 > 数据库

读取并显示数据库中的二进制图片(一张和一组)

2009-07-21 10:55 459 查看
1,一张需两个.aspx页面,分别为1.aspx,2.aspx。

1.aspx的后台代码为
<asp:Image ID="Image1" runat="server" Height="258px" Width="177px" />
protected void Page_Load(object sender, EventArgs e)
{
Image1.ImageUrl = "Register.aspx";
}


2.仅需前台代码就可:
public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string imgid = Request.QueryString["imgid"];
SqlConnection conn1 = new SqlConnection("Data Source=localhost;Initial Catalog=S601;User ID=sa;Password=123456");
SqlCommand cmd1 = new SqlCommand("select picture,pname,psize,pid from pictures where pid=1", conn1);
conn1.Open();
SqlDataReader sdr = cmd1.ExecuteReader();
if (sdr.Read())
{
Response.BinaryWrite((byte[])sdr["picture"]);
}
Response.End();
}


二,一组图片上传只需1.aspx一个页面的后台代码,和一个一般处理程序Getimg.ashx代码分别是:

<asp:DataGrid id="MyDataGrid" runat="server" AutoGenerateColumns="False" Width="632px">
<AlternatingItemStyle BackColor="Beige"></AlternatingItemStyle>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<Columns>
<asp:TemplateColumn HeaderText="Photo">
<ItemTemplate>  <asp:Image ID="Image1" runat="server" Height="70px" ImageUrl='<%# "Getimg.ashx?id="+Eval("pid") %>'
Width="100px" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:S601ConnectionString %>"
SelectCommand="SELECT pid, pname, psize, picture, ptype FROM pictures"></asp:SqlDataSource>


<%@ WebHandler Language="C#" Class="Getimg" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public class Getimg : IHttpHandler
{

public void ProcessRequest (HttpContext context) {
int id = int.Parse(context.Request.QueryString["id"]);
SqlConnection conn = new SqlConnection(@"Data Source=localhost;Initial Catalog=S601;User ID=sa;Password=123456");
SqlCommand cmd = new SqlCommand("select picture from pictures where pid='" + id + "'", conn);
cmd.Parameters.Add("@id",SqlDbType.Int).Value=id;
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
context.Response.BinaryWrite((byte[])dr["picture"]);
}
dr.Close();
}

public bool IsReusable {
get {
return false;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: