利用ajax方式下載文件

原本使用的是跳轉的方式直接下載文件,由於要加遮罩層,無法確定關閉遮罩層時間,所以採用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;
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章