ASP.NET 上传图片至数据库并读取图片显示--二进制流方式

时间:2022-11-13 00:05:57

以二进制流的方式存入数据库,并读取显示

数据库的字段同样简单:
Image_ID    int    identity(1,1)     primarykey    not null
Image_Content     image null
Image_Content以二进制形式保存图片

整体看一下例子里的页面组成:
上传图片页面和第一种方法一样,同样是用到FileUpload,以及一个Button,具体代码如下:

protected void Button1_Click(object sender, EventArgs e)

{

      
string name =
FileUpload1.PostedFile.FileName;

      
string type = name.Substring(name.LastIndexOf(".") + 1
);

        FileStream fs
=
File.OpenRead(name);

      
byte[] content = new byte
[fs.Length];

        fs.Read(content,
0
, content.Length);

        fs.Close();



        SqlConnection conn
= new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Pooling=False;Password="
);

        SqlCommand cmd
=
conn.CreateCommand();

        conn.Open();

        cmd.CommandText
= "insert into Images(Image_Content) values (@content)"
;

        cmd.CommandType
=
CommandType.Text;



      
if (type == "jpg" || type == "gif" || type == "bmp" || type == "png"
)

        {

          SqlParameter para
= cmd.Parameters.Add("@content"
, SqlDbType.Image);

          para.Value
=
content;

          cmd.ExecuteNonQuery();

        }

}

显示一张图片和显示一组图片有所不同,将会分别说明之。

显示一张图片,要用到Default.aspx和Default2.aspx。Default.aspx中有一个控件Image,它的属性ImageUrl指向Default2.aspx用于显示图片。Default2.aspx用于
读取图片。
Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)

{



        Image1.ImageUrl
= "Default2.aspx"
;

}

Default2.aspx.cs       

string imgid = Request.QueryString["imgid"
];

        SqlConnection conn1
= new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=sa;Pooling=False;Password="
);

        SqlCommand cmd1
= new SqlCommand("select Image_Content from Images where Image_ID=3", conn1);     //固定显示Image_ID为3的图片


        conn1.Open();

        SqlDataReader sdr
= cmd1.ExecuteReader();

      
if
(sdr.Read())

        {

          Response.BinaryWrite((
byte[])sdr["Image_Content"
]);

        }

        Response.End();

显示一组图片时,用ashx Handle存放图片。同时用GridView以列显示图片。Image控件绑定Image_ID。
allimage.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="allimage.aspx.cs" Inherits="allimage" %>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">



<HTML xmlns="http://www.w3.org/1999/xhtml">

<HEAD runat="server">


<title>BindImg</title>


</HEAD>


<body>


<form id="Form1" method="post" runat="server">


<FONT face="宋体">


<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("Image_ID") %>'


        Width
="100px" />

</ItemTemplate>

</asp:TemplateColumn>


</Columns>


</asp:DataGrid></FONT>


<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:PracticeConnectionString %>"


        SelectCommand
="SELECT * FROM [Images]"></asp:SqlDataSource>

</form>

</body>


</HTML>


allimage.aspx.cs

protected void Page_Load(object sender, EventArgs e)

{

        MyDataGrid.DataSource
=
SqlDataSource1;

        MyDataGrid.DataBind();

}
Getimg.ashx
<%@ 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(@"server=;database=;uid=;pwd="
);

        SqlCommand cmd
= new SqlCommand("select Image_Content from Images where Image_ID='" + id + "'"
, conn);

        cmd.Parameters.Add(
"@id", SqlDbType.Int).Value =
id;

        conn.Open();

        SqlDataReader dr
=
cmd.ExecuteReader();

      
if
(dr.Read())

        {

          context.Response.BinaryWrite((
byte[])dr["Image_Content"
]);

        }

        dr.Close();

}



public bool
IsReusable {

      
get
{

        
return false
;

        }

}

}

转载 http://blog.163.com/sdq_1314/blog/static/166908254201081704330711/