文件上传下载(实例)

在编写下载文件代码时,要注意一点。若是火狐浏览器,则不需要编码,要区别对待

直接上代码

 

  1 namespace 上传文件
  2 {
  3     public partial class WebForm1 : System.Web.UI.Page
  4     {
  5         public static string fileName = "";
  6         protected void Page_Load(object sender, EventArgs e)
  7         {
  8             if (!IsPostBack)
  9             {
 10                 BindDropDownList();
 11             }
 12         }
 13 
 14         //上传文件
 15         protected void Button1_Click(object sender, EventArgs e)
 16         {
 17             if (FileUpload1.HasFile)
 18             {
 19                 fileName = FileUpload1.FileName;
 20                 string result = fileUpload(fileName);
 21                 if (!string.IsNullOrEmpty(result))
 22                 {
 23                     Page.ClientScript.RegisterClientScriptBlock(Page.ClientScript.GetType(), "myscripts", "<script>alert(\"上传成功!\");</script>");
 24                     BindDropDownList();
 25                 }
 26                 else
 27                 {
 28                     Page.ClientScript.RegisterClientScriptBlock(Page.ClientScript.GetType(), "myscripts", "<script>alert(\"上传失败!\");</script>");
 29                 }
 30             }
 31         }
 32 
 33 
 34         /// <summary>
 35         /// 上传文件
 36         /// </summary>
 37         /// <param name="fileName">文件名称</param>
 38         /// <returns></returns>
 39         public static string fileUpload(string fileName)
 40         {
 41             string fileNewName = String.Empty;
 42             if (fileName.Length > 0)
 43             {
 44                 string fileExtension = Path.GetExtension(fileName).ToLower();
 45                 if (checkFileExtension(fileExtension))
 46                 {
 47                     //fileNewName = DateTime.Now.ToString("yyyyMMddhhmmss") + fileExtension;
 48                     fileNewName = fileName;
 49                     HttpPostedFile file = HttpContext.Current.Request.Files[0];
 50                     file.SaveAs(HttpContext.Current.Server.MapPath("File/" + fileNewName));
 51                 }
 52             }
 53             return fileNewName;
 54         }
 55 
 56         /// <summary>
 57         /// 检查上传文件格式是否正确
 58         /// </summary>
 59         /// <param name="fileExtension">文件扩展名</param>
 60         /// <returns></returns>
 61         public static bool checkFileExtension(string fileExtension)
 62         {
 63             string[] extensionArr = { ".doc", ".txt", ".pdf", ".rar", ".zip", ".docx", ".doc", ".ppt", ".png", ".gif", ".jpg", ".jpeg",".exe"};
 64             for (int i = 0; i < extensionArr.Length; i++)
 65             {
 66                 if (fileExtension == extensionArr[i])
 67                 {
 68                     return true;
 69                 }
 70             }
 71             return false;
 72         }
 73 
 74         //获取所有文件文件名
 75         public List<string> GetFileNames()
 76         {
 77             string path = Server.MapPath("File");
 78             DirectoryInfo dir = new DirectoryInfo(path);
 79             FileInfo[] files = dir.GetFiles();
 80             List<string> list = new List<string>();
 81             foreach (FileInfo item in files)
 82             {
 83                 list.Add(item.Name);
 84             }
 85             return list;
 86         }
 87 
 88         //绑定dropdownList
 89         private void BindDropDownList()
 90         {
 91             DropDownList1.DataSource = GetFileNames();
 92             DropDownList1.DataBind();
 93             DropDownList1.Items.Insert(0, "请选择文件");
 94         }
 95 
 96         //下载指定文件
 97         protected void Button2_Click(object sender, EventArgs e)
 98         {
 99             if(DropDownList1.SelectedIndex!=0)
100             {
101                 string fileName = DropDownList1.SelectedItem.ToString();//客户端保存的文件名
102                 string filePath = Server.MapPath("File/") + fileName;//路径
103                 DownLoadFile(fileName, filePath);
104             }
105             else
106             {
107                 Page.ClientScript.RegisterClientScriptBlock(Page.ClientScript.GetType(), "myscripts", "<script>alert(\"请选择下载文件!\");</script>");
108             }
109         }
110 
111 
112         /// <summary>
113         /// 文件下载
114         /// </summary>
115         /// <param name="fileName">文件名称</param>
116         /// <param name="filePath">文件绝对路径</param>
117         public void DownLoadFile(string fileName, string filePath)
118         {
119 
120             ////WriteFile分块下载
121             string browserType = Request.Browser.Browser.ToString();//获取浏览器类型
122 
123             string fileNewName = "";
124             if (browserType != "Firefox")//火狐浏览器不需要进行编码,文件名称就能显示
125             {
126                 fileNewName = HttpUtility.UrlEncode(fileName); //如果不是火狐浏览器,加上HttpUtility.UrlEncode()方法,防止文件下载时,文件名乱码
127             }
128             else
129             {
130                 fileNewName = fileName;
131             }
132 
133             System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
134 
135             if (fileInfo.Exists == true)
136             {
137                 const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
138                 byte[] buffer = new byte[ChunkSize];
139 
140                 Response.Clear();
141                 System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
142                 long dataLengthToRead = iStream.Length;//获取下载的文件总大小
143                 Response.ContentType = "application/octet-stream";
144                 Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
145 
146                 while (dataLengthToRead > 0 && Response.IsClientConnected)
147                 {
148                     int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小
149                     Response.OutputStream.Write(buffer, 0, lengthRead);
150                     Response.Flush();
151                     dataLengthToRead = dataLengthToRead - lengthRead;
152                 }
153                 Response.Close();
154                 
155             }
156         }
157   
158 
159     }
160 }
View Code

文件的下载方式有很多,具体可以参考:http://www.cnblogs.com/zhangzt/archive/2009/12/14/1623426.html

 

posted @ 2016-09-23 14:01  一抹嫣红  阅读(388)  评论(0编辑  收藏  举报