利用ajax方式下载文件

转载知识点 同时被 2 个专栏收录
28 篇文章 0 订阅
57 篇文章 0 订阅

原本使用的是跳转的方式直接下载文件,由于要加遮罩层,无法确定关闭遮罩层时间,所以采用ajax的方式下载文件

参考网址:进度条https://www.cnblogs.com/hjx-blog/p/6670978.html

ajax下载文件https://blog.csdn.net/q1328495705/article/details/72638643

后台方法:第一个方法生成压缩包并保存到一个地址下,把路径返回给前台,第二个方法是通过路径下载文件

public void BatchExport(List<string> param)
        {
            object path = "";         //文件路径变量
            string result = string.Empty;
            try
            {
                using (FileStream zipFile = System.IO.File.Create(Server.MapPath((string)path) + "/***.zip"))
                {
                    //ZipOutputStream zipStream = new ZipOutputStream(Response.OutputStream);
                    ZipOutputStream zipStream = new ZipOutputStream(zipFile);
                    try
                    {
                            MemoryStream strm = new MemoryStream();
                            report.Prepare();
                            report.Export(new PDFExport(), strm);
                            strm.Position = 0;
                            byte[] bytes = new byte[(int)strm.Length];
                            strm.Read(bytes, 0, bytes.Length);
                            strm.Close();
                            var zipEntry = new ZipEntry("测试.pdf");
                            zipStream.PutNextEntry(zipEntry);
                            zipStream.SetLevel(5);
                            zipStream.Write(bytes, 0, bytes.Length);
                        }
                    }
                    catch (Exception ex)
                    {
                        result = "{\"result\":\"fail\",\"message\":\"" + ex.Message + "\"}";
                    }
                    zipStream.Finish();
                    result = "{\"result\":\"success\",\"filePath\":\"" + HttpUtility.UrlEncode((string)path + "/***.zip") + "\"}";
                }
            }
            catch (Exception ex)
            {
                result = "{\"result\":\"fail\",\"message\":\""+ex.Message+"\"}";
            }
            Response.ContentType = "application/Json";
            Response.Write(result);
            Response.End();
        }
        public void DownLoadZip(string filePath)
        {
            FileInfo fileInfo = new FileInfo(Server.MapPath(HttpUtility.UrlDecode(filePath)));
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            String userAgent = System.Web.HttpContext.Current.Request.UserAgent;
            string fileName = "***.zip";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", fileName));
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.WriteFile(fileInfo.FullName);
            Response.Flush();
            Response.End();
        }

前台JS方法:

jQuery.download = function (url, method, filePath) {
            jQuery('<form action="' + url + '" method="' + (method || 'post') + '">' +  // action请求路径及推送方法
                '<input type="text" name="filePath" value="' + filePath + '"/>' + // 文件路径
                '</form>')
                .appendTo('body').submit().remove();
        };

$("#ContainDiv").show();
                var interval
                    var obj = { param: getParam() };
                    $.ajax({
                        type: 'POST',
                        async: true,//需要设置为true,不然遮罩层显示不出来
                        url: '/GridMember/BatchExport',// 生成文件,保存在服务器
                        data: obj,
                        beforeSend: function () {
                            var percentage = 0;
                            interval = setInterval(function () {
                                if (percentage < 8000) {
                                    percentage++;
                                    var widthTemp = (percentage / 100).toFixed(1) + '%';
                                    $('#progressBar').css('width', widthTemp);
                                    $('#progressBar').text(widthTemp);
                                } else {
                                    clearInterval(interval);
                                }
                            }, 10)
                        },
                        complete: function () {
                                clearInterval(interval);
                                $('#progressBar').css('width', '90%');
                                $('#progressBar').text('90%');
                        },
                        success: function (data) {
                            clearInterval(interval);
                            $('#progressBar').css('width', '80%');
                            $('#progressBar').text('80%');
                            var dataObj = JSON.parse(data);
                            if (dataObj.result == "success") {
                                $.download('/GridMember/DownLoadZip', 'post', dataObj.filePath); // 下载文件 
                                $("#ContainDiv").hide();
                            } else {
                                alert("数据导出失败!错误原因:" + dataObj.message);
                                $("#ContainDiv").hide();
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, e) {
                            //console.log("oilDetection.js  method exportOilDetection" + e);
                            alert("数据传输发生错误,请联系管理员!");
                            $("#ContainDiv").hide();
                        }
                    });

HTML代码

    <div style="top:0;left:0;bottom:0;right:0;opacity:0.4;background:#808080;width:100%;height:100%;z-index:10000;position: fixed;display:none" id="ContainDiv">
        <div class="flex-center">
            <h3 style="color:chartreuse">批量导出中,请稍等...</h3>
            <span class="icontainer">
                <span id="progressBar" class="h-100P bar"></span>
             </span>
        </div>
    </div>

css样式

 .flex-center{
            display: flex;
            flex-direction: column;
            align-items: center;
            position: absolute;
            left:50%;
            top:50%;
            transform: translate(-50%, -50%);
            width:100%;
            height:100px;
        }
        .icontainer{
                display: inline-block;
                width: 50%;
                height: 20px;
                padding-right: 10px;
                border: 1px solid #999;
                border-radius: 5px; 
                background:#999
        }
        .h-100P{
                height: 100%;
        }
        .bar{
                display: inline-block;
                background:#00ff21;
                color: white;
                font-weight: bold;
                padding: 0 5px;
                text-align: right;
                border-radius: 5px;
                border-right: 1px solid #999;
        }

 

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 扫一扫,分享海报

参与评论 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值