今天討論區有人問到這樣的需求..
小弟就做一個範例實做這樣的功能..
首先要準備的東西如下:
DB,結構如圖(table name:fileupload)
file,FileuploadGuid.aspxFileuploadGuid.aspx.csfiledownload.ashxfile(目錄)→存放檔案用
FileuploadGuid.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileuploadGuid.aspx.cs" Inherits="FileuploadGuid" %> <!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>FileuploadGuid</title> </head> <body> <form id="form1" runat="server"> <div> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" /> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1"> <Columns> <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" /> <asp:BoundField DataField="guid" HeaderText="guid" SortExpression="guid" /> <asp:BoundField DataField="filename" HeaderText="filename" SortExpression="filename" /> <asp:TemplateField HeaderText="download"> <ItemTemplate> <asp:HyperLink ID="HyperLink1" NavigateUrl='<%# "filedownload.ashx?guid="+Eval("guid") %>' runat="server">click</asp:HyperLink> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [fileupload]"></asp:SqlDataSource> </div> </form> </body> </html>
FileuploadGuid.aspx.cs
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using System.IO; public partial class FileuploadGuid : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnUpload_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { string guid = Guid.NewGuid().ToString(); string filename = this.FileUpload1.FileName; //存至Disk this.FileUpload1.SaveAs(Server.MapPath(string.Format(@"file\{0}.{1}", guid, Path.GetExtension(filename)))); //寫入DB using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString)) { string sql = "insert into [fileupload] ([guid],[filename]) values(@guid,@filename)"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.Add("guid", SqlDbType.Char, 36).Value = guid; cmd.Parameters.Add("filename", SqlDbType.NVarChar).Value = filename; conn.Open(); cmd.ExecuteNonQuery(); } } this.GridView1.DataBind(); } }
filedownload.ashx
<%@ WebHandler Language="C#" Class="filedownload" %> using System; using System.Web; using System.Data.SqlClient; using System.Data; using System.IO; using System.Configuration; public class filedownload : IHttpHandler { public void ProcessRequest(HttpContext context) { string guid = context.Request.QueryString["guid"] as string; //讀取DB using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString)) { string sql = "select * from [fileupload] where guid=@guid"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.Add("guid", SqlDbType.Char, 36).Value = guid; conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { string filename = dr["filename"].ToString(); context.Response.Buffer = true; context.Response.Clear(); context.Response.ContentType = "application/download"; context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ";"); context.Response.BinaryWrite(File.ReadAllBytes(context.Server.MapPath(string.Format(@"file\{0}.{1}", guid, Path.GetExtension(filename))))); context.Response.Flush(); context.Response.End(); } dr.Close(); } } public bool IsReusable { get { return false; } } }
執行結果:
參考網址:http://www.blueshop.com.tw/board/show.asp?subcde=BRD20090212105722WRJ&fumcde=FUM20041006161839LRJ#BRD20090212112634RZ4