標籤

more tags...

最新回覆

檔案直接從資料庫呼叫出來變成超連結作法

最近在小舖看到這篇文章...

就把它當作練習程式功力的題目來做....

這支程式主要的功能..如下...

1.利用Fileupload上傳檔案至資料庫

2.將資料庫的記錄以GridView顯示,並多一個Hyperlink帶參數結合ashx檔

3.利用ashx檔提供檔案下載的功能

資料庫規劃如下:

c#範例

FileList.aspx.aspx

01 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileList.aspx.cs" Inherits="FileList" %>
02
03 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04
05 <html xmlns="http://www.w3.org/1999/xhtml" >
06 <head runat="server">
07     <title>FileList</title>
08 </head>
09 <body>
10     <form id="form1" runat="server">
11     <div>
12         <asp:FileUpload ID="FileUpload1" runat="server" /><asp:Button ID="Button1"
13             runat="server" OnClick="Button1_Click" Text="upload" />
14         <br />
15         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White"
16             BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataKeyNames="id"
17             DataSourceID="SqlDataSource1" GridLines="Vertical" Width="265px">
18             <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
19             <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
20             <Columns>
21                 <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
22                     SortExpression="id" />
23                 <asp:BoundField DataField="filename" HeaderText="filename" SortExpression="filename" />
24                 <asp:TemplateField HeaderText="download">
25                     <ItemTemplate>
26                         <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# "FileDownload.ashx?id="+Eval("id") %>'>下載</asp:HyperLink>
27                     </ItemTemplate>
28                 </asp:TemplateField>
29             </Columns>
30             <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
31             <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
32             <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
33             <AlternatingRowStyle BackColor="#DCDCDC" />
34         </asp:GridView>
35         <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
36             SelectCommand="SELECT * FROM [fileTable]"></asp:SqlDataSource>
37     </div>    
38     </form>
39 </body>
40 </html>
41

FileList.aspx.cs

01 using System;
02 using System.Data;
03 using System.Configuration;
04 using System.Collections;
05 using System.Web;
06 using System.Web.Security;
07 using System.Web.UI;
08 using System.Web.UI.WebControls;
09 using System.Web.UI.WebControls.WebParts;
10 using System.Web.UI.HtmlControls;
11 using System.Data.SqlClient;
12
13 public partial class FileList : System.Web.UI.Page
14 {
15     protected void Page_Load(object sender, EventArgs e)
16     {
17
18     }

19     protected void Button1_Click(object sender, EventArgs e)
20     {
21         //判斷檔案是否存在
22         if (this.FileUpload1.HasFile)
23         {
24
25             //寫入資料庫
26             using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))

27             {
28                 string sql = "insert into [fileTable] ([filename],[filedata]) values(@filename,@filedata)";
29                 SqlCommand cmd = new SqlCommand(sql, conn);
30                 cmd.Parameters.Add("@filename", SqlDbType.NVarChar, 50).Value = this.FileUpload1.FileName;
31                 byte[] filebyte = new byte[this.FileUpload1.PostedFile.InputStream.Length];
32                 this.FileUpload1.PostedFile.InputStream.Read(filebyte, 0, filebyte.Length);
33                 cmd.Parameters.Add("@filedata", SqlDbType.Image).Value = filebyte;
34                 conn.Open();
35                 cmd.ExecuteNonQuery();
36                 this.GridView1.DataBind();
37             }

38         }

39     }

40 }

41

FileDownload.ashx

01 <%@ WebHandler Language="C#" Class="FileDownload" %>
02
03 <%@ WebHandler Language="C#" Class="FileDownload" %>
04
05 using System;
06 using System.Web;
07 using System.Data.SqlClient;
08 using System.Data;
09 using System.Configuration;
10
11 public class FileDownload : IHttpHandler {
12     
13     public void ProcessRequest (HttpContext context)
14     {
15         int id = int.Parse(context.Request.QueryString["id"]);
16         using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))

17         {
18             string sql = "select * from [fileTable] where id=@id";
19             SqlCommand cmd = new SqlCommand(sql, conn);
20             cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
21             conn.Open();
22             SqlDataReader dr = cmd.ExecuteReader();
23             if (dr.Read())
24             {
25                 context.Response.Buffer = true;
26                 context.Response.Clear();
27                 context.Response.ContentType = "application/download";
28                 context.Response.AddHeader("Content-Disposition", "attachment;   filename=" + dr["filename"].ToString() + ";");
29                 context.Response.BinaryWrite((byte[])dr["filedata"]);
30                 context.Response.Flush();
31                 context.Response.End();  
32             }

33             dr.Close();
34         }

35     }

36
37     public bool IsReusable {
38         get {
39             return false;
40         }

41     }

42
43 }

執行結果:

參考網址:
http://www.blueshop.com.tw/board/show.asp?subcde=BRD20060918005956WX6&fumcde=FUM20041006161839LRJ
http://topic.csdn.net/t/20030214/15/1428787.html
http://blog.blueshop.com.tw/hent/archive/2008/03/10/54480.aspx

推到 Twitter!
推到 Plurk!


 

2008/3/12 23:56| 閱讀數 : 5785 | 1 人收藏 我要推薦 | 6 Comments | 文章分類 : ASP.NET ASP.NET(FileUpload) ASP.NET(GridView) ASP.NET(Handle) 訂閱


回覆

# re: 檔案直接從資料庫呼叫出來變成超連結作法, Posted by sr713107 on 2008/6/10 下午 06:03  回覆

好東西,請教一下,如果我要上傳的檔案想要指定到不同的目錄,象會計室有自己的目錄,資訊室有自己的目錄,請問要怎麼寫?

# re: 檔案直接從資料庫呼叫出來變成超連結作法, Posted by student on 2008/6/23 下午 06:57  回覆

你好!我想請問一下 如果想要讓filename本身就是超連結
而不要download的下載 這樣應該怎麼做呢

# re: 檔案直接從資料庫呼叫出來變成超連結作法, Posted by puma on 2008/7/31 下午 01:35  回覆

解決中文檔名問題

Response.AddHeader("content-disposition", "attachment;filename=" & HttpUtility.UrlEncode(filename))

參考網址:

http://blog.darkthread.net/blogs/darkthreadtw/archive/2007/09/05/kb-open-and-download-file-in-chinese-filename.aspx

# re: 檔案直接從資料庫呼叫出來變成超連結作法, Posted by Jacky on 2009/5/8 下午 06:18  回覆

如要做成選擇後整批下載功能,應如何修改?

# re: 檔案直接從資料庫呼叫出來變成超連結作法, Posted by puma on 2009/5/11 上午 08:23  回覆

to Jacky,

整批下載喔,我想在gridview多一個checkbox欄位,

先勾選要下載的檔案,然後把那些檔案壓縮起來,

然後輸出那個壓縮檔給使用者下載..這是我大概的想法..沒實作過..

你可以試試訝..

# re: 檔案直接從資料庫呼叫出來變成超連結作法, Posted by Charles on 2009/7/10 下午 04:02  回覆

照樓主的程式碼打下去,發現hyperlink 的NavigateUrl 屬性字串有點問題,開發環境會出現:....轉換成Double時出現錯誤......
改成底下這樣就可以過關了....
NavigateUrl='<%# "FileDownload.ashx?id="+Convert.ToString(Eval("id")) %>'

發表回覆

標題: *
姓名: *
Email: (將不會被顯示)
Url:
回覆: *
登入後使用進階評論
Please add 5 and 7 and type the answer here:
F6 Team logo


用BloggerAds 替自已加薪

每月文章

文章分類

推薦討論區

推薦部落格