ASP.NET 文件的上传与下载
前端页面:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileOption.aspx.cs" Inherits="FileOption" %> 2 3 <!DOCTYPE html> 4 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 8 <title></title> 9 <style type="text/css"> 10 .auto-style1 { 11 width: 100%; 12 } 13 .auto-style2 { 14 width: 121px; 15 } 16 </style> 17 </head> 18 <body> 19 <form id="form1" runat="server"> 20 <div> 21 22 <table class="auto-style1"> 23 <tr> 24 <td class="auto-style2">文件名称:</td> 25 <td> 26 <asp:TextBox ID="txtFileName" runat="server"></asp:TextBox> 27 </td> 28 </tr> 29 <tr> 30 <td class="auto-style2">浏览:</td> 31 <td><asp:FileUpload ID="UploadFile" runat="server"/></td> 32 </tr> 33 <tr> 34 <td class="auto-style2"> </td> 35 <td> 36 <asp:Button ID="btnFile" runat="server" OnClick="btnFile_Click" Text="上传" /> 37 <asp:Label ID="msg" runat="server" ForeColor="Red"></asp:Label> 38 </td> 39 </tr> 40 </table> 41 </div> 42 <asp:Repeater ID="Repeater1" runat="server" onitemcommand="down_file_Click"> 43 <ItemTemplate> 44 <table> 45 <tr> 46 <td >文件名称:</td> 47 <td><b><asp:Label ID="FileTitle" runat="server" Text='<%#Eval("文件名称") %>'></asp:Label></b></td> 48 <td>类型:</td> 49 <td><%#Eval("类型") %></td> 50 <td>文件大小:</td> 51 <td><%#Eval("文件大小") %>KB</td> 52 <td>上传时间:</td> 53 <td ><%#Eval("上传时间") %></td> 54 <td ><asp:LinkButton ID="LinkButton1" CommandArgument='<%#Eval("link") %>' runat="server">下载文件</asp:LinkButton> </td> 55 </tr> 56 </table> 57 <br /> 58 </ItemTemplate> 59 </asp:Repeater> 60 </form> 61 </body> 62 </html>
后台实现代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Web.UI.WebControls; 7 using System.IO; 8 using System.Data; 9 using System.Text; 10 11 public partial class FileOption : System.Web.UI.Page 12 { 13 protected void Page_Load(object sender, EventArgs e) 14 { 15 GrvDataBin(FindFile()); 16 } 17 /// <summary> 18 /// 上传文件 19 /// </summary> 20 /// <param name="sender"></param> 21 /// <param name="e"></param> 22 protected void btnFile_Click(object sender, EventArgs e) 23 { 24 msg.Text = ""; 25 //自定义的 File 类 26 File file = new File(); 27 if (string.IsNullOrEmpty(txtFileName.Text)) 28 { 29 msg.Text = "请输入文件名称!"; 30 return; 31 } 32 if (UploadFile.HasFile) 33 { 34 try 35 { 36 DateTime upload = DateTime.Now; 37 //获取文件的扩展名(文件类型) 38 string type = Path.GetExtension(UploadFile.PostedFile.FileName); 39 //设置上传文件的路径 40 string path = Server.MapPath("Upload/" + txtFileName.Text + type); 41 //获取文件的大小 42 string size = (UploadFile.PostedFile.ContentLength / 1024).ToString(); 43 //保存文件(保存到服务器指定路径中) 44 UploadFile.SaveAs(path); 45 msg.Text = "上传成功!"; 46 //上传成功后更新数据 47 GrvDataBin(FindFile()); 48 } 49 catch (Exception err) 50 { 51 msg.Text = "上传失败!" + err.Message; 52 } 53 } 54 else 55 msg.Text = "请选择文件!"; 56 } 57 /// <summary> 58 /// 获取指定目录下的所有文件的集合 59 /// </summary> 60 /// <returns>返回一个File类的集合</returns> 61 private List<File> FindFile() 62 { 63 string path = Server.MapPath("Upload/");//获取文件所在目录 64 string[] paths = Directory.GetFiles(path);//获取目录中所有文件路径 65 List<File> list = new List<File>(); 66 foreach(string filePath in paths) 67 { 68 string size = 0.ToString(); 69 string time = DateTime.Now.ToShortTimeString(); 70 GetFileSize(filePath,out size,out time); 71 File file = new File(filePath,size,time); 72 list.Add(file); 73 } 74 return list; 75 } 76 /// <summary> 77 /// 绑定文件数据信息 78 /// </summary> 79 /// <param name="list">传入的文件集合</param> 80 public void GrvDataBin(List<File> list) 81 { 82 83 DataView dv = new DataView(); 84 DataTable dt = new DataTable("fileMeta"); 85 { 86 dt.Columns.Add("文件名称"); 87 dt.Columns.Add("类型"); 88 dt.Columns.Add("上传时间"); 89 dt.Columns.Add("文件大小"); 90 dt.Columns.Add("link"); 91 } 92 foreach (File fileM in list) 93 { 94 DataRow row = dt.NewRow(); 95 row[0] = fileM.FileName; 96 row[1] = fileM.Type; 97 row[2] = fileM.UploadTime; 98 row[3] = fileM.Size; 99 row[4] = fileM.FilePath; 100 dt.Rows.Add(row); 101 } 102 dv.Table = dt; 103 Repeater1.DataSource = dv; 104 Repeater1.DataBind(); 105 } 106 /// <summary> 107 /// 获取文件大小和时间 108 /// </summary> 109 /// <param name="filePath"></param> 110 /// <returns></returns> 111 private string GetFileSize(string filePath,out string size,out string time) 112 { 113 FileInfo file = new FileInfo(filePath); 114 size =(Convert.ToDouble(file.Length)/1024.0).ToString("0.00"); 115 time = file.CreationTime.ToShortTimeString(); 116 return null; 117 } 118 /// <summary> 119 /// 文件下载 120 /// </summary> 121 /// <param name="sender"></param> 122 /// <param name="e"></param> 123 protected void down_file_Click(object sender, RepeaterCommandEventArgs e) 124 {//注释的为流下载 125 //FileStream fs = null; 126 try 127 { 128 // 获取文件的路径 129 string filePath = e.CommandArgument.ToString(); 130 // 获取文件的名称 131 string fileName = ((Label)e.Item.FindControl("FileTitle")).Text.ToString(); 132 //fs = System.IO.File.OpenRead(filePath); 133 //long count = 1024; 134 //byte[] buffer = new byte[count]; 135 //Response.Buffer = true; 136 // 设置输出流的 MIME 类型 137 Response.ContentType = "application/octet-stream"; 138 // 通知浏览器下载而不是打开 139 Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(fileName));//下载时要保存的默认文件名 140 //while (count == 1024) 141 //{ 142 // count = fs.Read(buffer, 0, 1024); 143 // Response.BinaryWrite(buffer); 144 // Response.Flush(); 145 // Response.End(); 146 //} 147 Response.TransmitFile(filePath); 148 Response.Flush(); 149 Response.End(); 150 } 151 catch (Exception) 152 { 153 return; 154 } 155 finally 156 { 157 //fs.Close(); 158 } 159 160 } 161 }
自定义的File 类用于保存文件的属性
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; /// <summary> /// File 的摘要说明 /// 自定义的文件信息类 /// </summary> public class File { #region private prop private string fileName; private string type; private string size; private string filePath; private string uploadTime; #endregion #region public prop public string Type { get { return type; } set { type = value; } } public string Size { get { return size; } set { size = value; } } public string FilePath { get { return filePath; } set { filePath = value; } } public string UploadTime { get { return uploadTime; } set { uploadTime = value; } } public string FileName { get { return fileName; } set { fileName = value; } } #endregion public File() { //初始化文件大小 Size = (1024 * 1024).ToString(); } public File(string filePath,string size,string time) { FilePath = filePath; string[] names = filePath.Split('\\'); FileName = names[names.Length-1]; Type = filePath.Split('.')[1]; Size = size; UploadTime = time; } }
这样简单的文件上传与下载就完成了。。。。
附上效果图:
文章未经版主同意不可任意转载,如有需要请标明文章出处。