ajax 实现文件下载

时间:2025-03-19 08:04:59



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

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

         }
    </script>




后台代码

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

                if ()//判断文件是否存在
                {
                    ();
                    ();
                    = false;
                    ("content-disposition", "attachment;filename=" + );
                    ("cintent_length", "attachment;filename=" + ());
                    ("cintent_length", ());
                    = "application/octet-stream";
                    ();//通过response对象,执行下载操作
                    ();
                    ();
                   
                }
               
            }
            catch(Exception e)
            {
                (());
            }

        }