ASP.NET上傳圖片至數(shù)據(jù)庫(kù)并顯示圖片
今天,和大家討論一下在ASP.NET中,如何上傳圖片至數(shù)據(jù)庫(kù),然后再將圖片讀取顯示的問題。歡迎高手提出自己的方法?。。?/P>
目前,我主要用到以下兩種方法:
1:上傳圖片的相對(duì)路徑到數(shù)據(jù)庫(kù)中相應(yīng)字段里,讀取顯示時(shí),將控件(假設(shè)用的是Image控件)的ImageUrl屬性指向該相對(duì)路徑即可。
2:將圖片以二進(jìn)制流的方式整體上傳到數(shù)據(jù)庫(kù)里,讀取顯示時(shí),以二進(jìn)制流的方式整體讀出。這種方法稍微麻煩一點(diǎn),但保存的是圖片整體到數(shù)據(jù)庫(kù)里。
***種方法,實(shí)現(xiàn)起來比較簡(jiǎn)單,因?yàn)榇嫒霐?shù)據(jù)庫(kù)里的只是圖片相對(duì)路徑,當(dāng)然,同時(shí)也就有很大的局限性,由于是相對(duì)路徑,所以當(dāng)本地的圖片變換了位置
或移除,或是在其他主機(jī)上瀏覽該圖片時(shí),就無法顯示了。第二種方法,就比較靈活了,可以用在交互性的頁(yè)面,比如校友錄,因?yàn)樯蟼鞯氖钦麖垐D片,所以只要讀取正確,就能任何主機(jī)上顯示出來。
下面,分別通過實(shí)際的代碼,介紹這兩種方法。
在這兩個(gè)方法里,我將用到一個(gè)控件:FileUpload,該控件的具體用法參見百度谷歌。。。學(xué)習(xí)過程中,***的老師就是他們倆。
1:ASP.NET上傳圖片上傳圖片相對(duì)路徑,并讀取顯示。
數(shù)據(jù)庫(kù)里的字段很簡(jiǎn)單,就兩個(gè)
Image_ID int identity(1,1) primarykey not null
Image_Wpath varchar(50) null
Image_Wpath 用來保存圖片的相對(duì)路徑
很簡(jiǎn)單的界面(其實(shí)是有點(diǎn)丑。。。。):
這里注意,我需要上傳的文件都放在文件夾“Image”,在后面的上傳路徑里就需要這個(gè)文件夾。
下面是效果圖:
我在輸入框里填入Image_ID的值,讀取指定的圖片,在圖片的下面,顯示出該圖片的相對(duì)路徑。
接下來,我們看一下具體代碼實(shí)現(xiàn)上傳和讀取顯示功能。
在項(xiàng)目里,有一個(gè)sqlHelper類,是一些常用的數(shù)據(jù)訪問方法。這里就不詳細(xì)講了。
上傳按鈕里的事件:
CODE:
- protected void Button1_Click(object sender, EventArgs e)
- {
- string name = FileUpload1.FileName;//獲取文件名
- string type = name.Substring(name.LastIndexOf(".") + 1);
- //獲取文件類型
- string ipath = Server.MapPath("Image") + "\\" + name;
- //獲取文件路徑
- string wpath = "Image\\" + name;
- //[color=red]設(shè)置文件保存相對(duì)路徑
- (這里的路徑起始就是我們存放圖片的文件夾名)[/color]
- string query1 = "insert into Images values
- ('" + wpath + "')";
- if (type == "jpg" || type == "gif" ||
- type == "bmp" || type == "png")
- {
- FileUpload1.SaveAs(ipath); //服務(wù)器保存路徑
- sqlHelper.ExecterNonQuery(query1);
- }
- }
顯示按鈕事件:
CODE:
- protected void Button2_Click(object sender, EventArgs e)
- {
- string query2 = "select * from Images where
- Image_ID=" + Convert.ToInt32(TextBox1.Text);
- SqlDataReader sdr = sqlHelper.GetReader(query2);
- string wpath2 = "";
- while (sdr.Read())
- {
- wpath2 = sdr[1].ToString();
- //獲得相對(duì)路徑
- }
- sdr.Close();
- Image1.ImageUrl = wpath2;
- //圖片顯示路徑就是相對(duì)路徑
- Label1.Text = wpath2; //顯示相對(duì)路徑
- }
2:以二進(jìn)制流的方式存入數(shù)據(jù)庫(kù),并讀取顯示圖片。
數(shù)據(jù)庫(kù)的字段同樣簡(jiǎn)單:
Image_ID int identity(1,1) primarykey not null
Image_Content image null
Image_Content以二進(jìn)制形式保存圖片
整體看一下例子里的頁(yè)面組成:
ASP.NET上傳圖片頁(yè)面和***種方法一樣,同樣是用到FileUpload,以及一個(gè)Button,具體代碼如下:
CODE:
- 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();
- }
- }
顯示一張圖片和顯示一組圖片有所不同,將會(huì)分別說明之。
顯示一張圖片,要用到Default.aspx和Default2.aspx。Default.aspx中有一個(gè)控件Image,它的屬性ImageUrl指向Default2.aspx用于顯示圖片。
Default2.aspx用于讀取圖片。
Default.aspx.cs
CODE:
- protected void Page_Load(object sender, EventArgs e)
- {
- Image1.ImageUrl = "Default2.aspx";
- }
Default2.aspx.cs
CODE:
- 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();
顯示一組圖片時(shí),用ashx Handle存放圖片。同時(shí)用GridView以列顯示圖片。Image控件綁定Image_ID。
allimage.aspx
CODE:
- 〈%@ 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
CODE:
- protected void Page_Load(object sender, EventArgs e)
- {
- MyDataGrid.DataSource = SqlDataSource1;
- MyDataGrid.DataBind();
- }
Getimg.ashx
CODE:
- 〈%@ 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;
- }
- }
- }
總結(jié):
兩種ASP.NET上傳圖片及讀取顯示方法,各有優(yōu)點(diǎn),個(gè)人更傾向于用第二種。因?yàn)榈诙N方法達(dá)到了真正的將圖片上傳到數(shù)據(jù)庫(kù)。在某些項(xiàng)目中,我們也可能要用到***種方法。本例中,沒有嚴(yán)格的判斷圖片上傳的格式,學(xué)習(xí)的朋友可以自己做嚴(yán)格判斷,防止上傳的是有害文件。
【編輯推薦】