http://www.dotblogs.com.tw/puma/archive/2009/02/12/7126.aspx

 

今天討論區有人問到這樣的需求..

小弟就做一個範例實做這樣的功能..

首先要準備的東西如下:

DB,結構如圖(table name:fileupload)


file,
FileuploadGuid.aspx
FileuploadGuid.aspx.cs
filedownload.ashx
file(目錄)→存放檔案用

FileuploadGuid.aspx

 

01 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileuploadGuid.aspx.cs" Inherits="FileuploadGuid" %>
02   
03 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04 <html xmlns="http://www.w3.org/1999/xhtml">
05 <head runat="server">
06     <title>FileuploadGuid</title>
07 </head>
08 <body>
09     <form id="form1" runat="server">
10         <div>
11             <asp:FileUpload ID="FileUpload1" runat="server" />
12             <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
13             <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
14                 DataSourceID="SqlDataSource1">
15                 <Columns>
16                     <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
17                         SortExpression="id" />
18                     <asp:BoundField DataField="guid" HeaderText="guid" SortExpression="guid" />
19                     <asp:BoundField DataField="filename" HeaderText="filename" SortExpression="filename" />
20                     <asp:TemplateField HeaderText="download">
21                         <ItemTemplate>
22                             <asp:HyperLink ID="HyperLink1" NavigateUrl='<%# "filedownload.ashx?guid="+Eval("guid") %>'
23                                 runat="server">click</asp:HyperLink>
24                         </ItemTemplate>
25                     </asp:TemplateField>
26                 </Columns>
27             </asp:GridView>
28             <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
29                 SelectCommand="SELECT * FROM [fileupload]"></asp:SqlDataSource>
30         </div>
31     </form>
32 </body>
33 </html>

 

FileuploadGuid.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 using System.IO;
13   
14 public partial class FileuploadGuid : System.Web.UI.Page
15 {
16     protected void Page_Load(object sender, EventArgs e)
17     {
18   
19     }
20     protected void btnUpload_Click(object sender, EventArgs e)
21     {
22         if (FileUpload1.HasFile)
23         {
24             string guid = Guid.NewGuid().ToString();
25             string filename = this.FileUpload1.FileName;
26   
27             //存至Disk
28             this.FileUpload1.SaveAs(Server.MapPath(string.Format(@"file\{0}.{1}", guid, Path.GetExtension(filename))));
29   
30   
31             //寫入DB
32             using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
33             {
34                 string sql = "insert into [fileupload] ([guid],[filename]) values(@guid,@filename)";
35                 SqlCommand cmd = new SqlCommand(sql, conn);
36                 cmd.Parameters.Add("guid", SqlDbType.Char, 36).Value = guid;
37                 cmd.Parameters.Add("filename", SqlDbType.NVarChar).Value = filename;
38                 conn.Open();
39                 cmd.ExecuteNonQuery();
40             }
41         }
42   
43         this.GridView1.DataBind();
44     }
45 }

 

filedownload.ashx

 

01 <%@ WebHandler Language="C#" Class="filedownload" %>
02   
03 using System;
04 using System.Web;
05 using System.Data.SqlClient;
06 using System.Data;
07 using System.IO;
08 using System.Configuration;
09   
10 public class filedownload : IHttpHandler
11 {
12   
13     public void ProcessRequest(HttpContext context)
14     {
15         string guid = context.Request.QueryString["guid"] as string;
16         //讀取DB
17         using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
18         {
19             string sql = "select * from [fileupload] where guid=@guid";
20             SqlCommand cmd = new SqlCommand(sql, conn);
21             cmd.Parameters.Add("guid", SqlDbType.Char, 36).Value = guid;
22             conn.Open();
23             SqlDataReader dr = cmd.ExecuteReader();
24             if (dr.Read())
25             {
26                 string filename = dr["filename"].ToString();
27   
28                 context.Response.Buffer = true;
29                 context.Response.Clear();
30                 context.Response.ContentType = "application/download";
31                 context.Response.AddHeader("Content-Disposition", "attachment;   filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ";");
32                 context.Response.BinaryWrite(File.ReadAllBytes(context.Server.MapPath(string.Format(@"file\{0}.{1}", guid, Path.GetExtension(filename)))));
33                 context.Response.Flush();
34                 context.Response.End();
35             }
36             dr.Close();
37         }
38     }
39   
40     public bool IsReusable
41     {
42         get
43         {
44             return false;
45         }
46     }
47   
48 }

 


執行結果:

參考網址:
http://www.blueshop.com.tw/board/show.asp?subcde=BRD20090212105722WRJ&fumcde=FUM20041006161839LRJ#BRD20090212112634RZ4
 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 meltdown 的頭像
    meltdown

    meltdown

    meltdown 發表在 痞客邦 留言(0) 人氣()