using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; public partial class DownFile : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack)//the first time to load { //get all the file in File folder String[] AllTxt = Directory.GetFiles(Server.MapPath("File")); foreach (String name in AllTxt) { ListBox1.Items.Add(Path.GetFileName(name)); } } } protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) { //make use of sssion to save the selected file in the listbox with the key of "select" Session["select"] = ListBox1.SelectedValue.ToString(); } protected void ImageButton_Down_Click(object sender, ImageClickEventArgs e) { //judge weather user choose at least one file if (ListBox1.SelectedValue != "") { //get the path of the choosed file String FilePath = Server.MapPath("File/") + Session["select"].ToString(); //initial the object of Class FileInfo and make it as the package path FileInfo filepathinfo = new FileInfo(FilePath); //judge weather the file exists if (filepathinfo.Exists) { //save the file to local Response.Clear(); Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(filepathinfo.Name)); Response.AddHeader("Content-length", filepathinfo.Length.ToString()); Response.ContentType = "application/octet-stream"; Response.Filter.Close(); Response.WriteFile(filepathinfo.FullName); Response.End(); } else { Page.RegisterStartupScript("sb", "<script>alert('Please choose one file,sir!')</script>"); } } } protected void ImageButton_Up_Click(object sender, ImageClickEventArgs e) { Response.Redirect("Default.aspx"); } }
注意:
最终的上传的文件将会在根目录下的File文件夹下看到,下载的时候也是从这个文件夹下进行下载的。
总结:
经过这个小项目的实践,我看到了session给编程带来的便利,也体会到了FileUpload控件的威力;然而这并不是全部,这里仅仅是冰山一角而已,希望大家继续学习,一起进步一起提高!