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

 下载文件是从网络中获得文件资源的主要手段,在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();//清空
                }
                else
                {
                    Response.Write("文件不存在");
                }
            }
            catch(Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

效果如下

这部分代码在down下,https://github.com/1126048156/upanddownfile.git


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值