ajax 实现文件下载




<script type="text/javascript">
        function DownLoad(strUrl) {
            var form = $("<form>");   //定义一个form表单
            form.attr('style', 'display:none');   //在form表单中添加查询参数
            form.attr('target', '');
            form.attr('method', 'post');
            form.attr('action', "/QuestionInfo/DowmLoad");

            var input1 = $('<input>');
            input1.attr('type', 'hidden');
            input1.attr('name', 'strUrl');
            input1.attr('value', strUrl);
            $('body').append(form);  //将表单放置在web中
            form.append(input1);   //将查询参数控件提交到表单上
            form.submit();

         }
    </script>




后台代码

 #region 文档下载
        /// <summary>
        /// 文件下载函数
        /// </summary>
        /// <param name="fileUrl"></param>
        /// <returns></returns>
        [HttpPost]
        public void  DowmLoad(string strUrl)
        {
            try
            {
                string fullPathUrl = Server.MapPath(strUrl);//获取下载文件的路劲
                System.IO.FileInfo file = new System.IO.FileInfo(fullPathUrl);

                if (file.Exists)//判断文件是否存在
                {
                    Response.Clear();
                    Response.ClearHeaders();
                    Response.Buffer = false;
                    Response.AddHeader("content-disposition", "attachment;filename=" + file.Name);
                    Response.AddHeader("cintent_length", "attachment;filename=" + HttpUtility.UrlDecode(file.Name));
                    Response.AddHeader("cintent_length", file.Length.ToString());
                    Response.ContentType = "application/octet-stream";
                    Response.WriteFile(file.FullName);//通过response对象,执行下载操作
                    Response.Flush();
                    Response.End();
                   
                }
               
            }
            catch(Exception e)
            {
                Console.Write(e.ToString());
            }

        }

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值