您的位置:首页 > 编程语言 > ASP

(九)上传和下载模块(下载文件)

2018-03-28 20:27 176 查看
 下载文件是从网络中获得文件资源的主要手段,在assp.net中没有提供下载文件的控件,但可以通过filestream流的方式和response对象的write()方法,编写下载函数实现下载文件的操作。
页面加载的时候,要将服务器里面的文件通过listbox展示出来。
protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                string strfilepath = Server.MapPath("~/morefile/");//获取路径
                DirectoryInfo dir = new DirectoryInfo(strfilepath);//创建目录对象
                FileSystemInfo[] files = dir.GetFileSystemInfos();//获取该目录下的所有文件
                ListItem items;
                foreach (FileSystemInfo infofiles in files)
                {
                    items = new ListItem();
                    items.Text = infofiles.Name;
                    items.Value = infofiles.FullName;
                    ListBox1.Items.Add(items);
                }

            }
然后,我们开始写下载
protected void Button1_Click(object sender, EventArgs e)
        {
            string road = "morefile/"+ListBox1.SelectedItem.Text;
            try
            {
                string url = Server.MapPath(road);//获得绝对下载路径
                FileInfo file = new FileInfo(url);//获得硬盘上该文件的详细信息
                if (file.Exists)
                {
                    Response.Clear();//清空response对象中的内容
                    //通过response对象执行下载文件的操作
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlDecode(file.Name));//HttpUtility.UrlDecode解决下载框的中文乱码
                    Response.AddHeader("Content-Length",file.Length.ToString());
                    Response.ContentType="application/application/octet-stream";
                    Response.WriteFile(file.FullName);
                    Response.End();//结束response对象
                    Response.Flush();//刷新
                    Response.Clear();//清空
                }
4000

                else
                {
                    Response.Write("文件不存在");
                }
            }
            catch(Exception ex)
            {
                Response.Write(ex.Message);
            }

        }
效果如下





这部分代码在down下,https://github.com/1126048156/upanddownfile.git
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  asp.net