在ASP.NET中完成文件下载后不执行JavaScript

yptwkmov  于 12个月前  发布在  .NET
关注(0)|答案(2)|浏览(129)

我在OnClientClick上调用loader,当下载过程正在进行时,它正在加载。但是当我试图在下载过程完成后隐藏加载器时,它不起作用。加载器继续显示和加载。
这里是代码。

function showloadingGif_UPLOAD() {
            document.getElementById('ContentPlaceHolder1_divShowLoadingGif').style.display = 'inline';
            return true;
        }

        function HideLoader() {
            document.getElementById('ContentPlaceHolder1_divShowLoadingGif').style.display = 'none';
        }

个字符
下面是调用hide函数的服务器端代码。

protected void btnDownloadInfo_Click(object sender, EventArgs e)
    {
        DataTable dtExcelData = new DataTable();
        try
        {
            CommonUser ObjUser = new CommonUser();
            string strDateFilter = txtDateSelection.Value;
            dtExcelData = ObjUser.GET_EXCEL_REPORT(strDateFilter);

            CommonDB.WriteLog("Dt Count 1 : " + dtExcelData.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());

            if (dtExcelData != null && dtExcelData.Rows.Count > 0)
            {
                CommonDB.WriteLog("Dt Count 2 : " + dtExcelData.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
                DownloadReport(dtExcelData);                    
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, GetType(), "disp_confirm", "<script>HideLoader()</script>", false);
                CommonDB.WriteLog("Dt Count 3 : " + dtExcelData.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
                ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('No record found');", true);
            }

        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(Page, GetType(), "disp_confirm", "<script>HideLoader()</script>", false);
            string strErrorMsg = ex.Message.ToString() + " " + "StackTrace :" + ex.StackTrace.ToString();
            CommonDB.WriteLog("ERROR:" + strErrorMsg, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
        }
    }

public static void DownloadReport(DataTable dtRecord)
    {
        try
        {
           
            string strFilename = string.Empty;
            
            using (XLWorkbook wb = new XLWorkbook())
            {
                CommonDB.WriteLog("Dt Count 3 : " + dtRecord.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
                wb.Worksheets.Add(dtRecord, "SheetName");
                strFilename = DateTime.Now.ToString();

                CommonDB.WriteLog("Dt Count 4 : " + dtRecord.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());

                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.Charset = "";
                HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=JIO_LOS_REPORT_"+ strFilename +".xlsx");
                CommonDB.WriteLog("Dt Count 5 : " + dtRecord.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
                
                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    CommonDB.WriteLog("Dt Count 6 : " + dtRecord.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
                    wb.SaveAs(MyMemoryStream);
                    MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
                    HttpContext.Current.Response.Flush();
                    HttpContext.Current.Response.End();
                    CommonDB.WriteLog("Dt Count 7 : " + dtRecord.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());                       
                }
            }
        }
        catch (Exception ex)
        {   
            string strErrorMsg = ex.Message.ToString() + " " + "StackTrace :" + ex.StackTrace.ToString();
            CommonDB.WriteLog("ERROR:" + strErrorMsg, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
        }
    }

brgchamk

brgchamk1#

这不是一个简单的解决方案...

  • 一个常规的回发请求(一个按钮的点击)-应该以一个新的整个页面呈现结果结束(+由一个名为Response.Write + Response.End的框架);
  • 一个文件下载回发请求-也应该以响应头=“attachmnent”(+由手动调用的Response.BinaryWrite + Response.End)结束;等等。

实际上,HttpContext.Current.Response.End();之后的所有内容对客户端/浏览器都没有影响。这就是为什么所有可能的ScriptManager.RegisterStartupScript调用都不是响应的一部分。因此,计划的JavaScript代码不会被评估/执行。当然,您可以尝试在代码中省略此调用,但有必要关注可能的副作用(以模拟“原生”响应.End)。
无论您在服务器端创建附件的方式如何,都必须正确(同步)下载附件。
这里的主要挑战是通知最终用户有关(可能)长时间(同步)操作。您可能会看到不同类型的弹出窗口或新打开的页面,其中包含“. your download will start sortly.”UI。
如果谈论你的代码,这个解决方案可以像这样实现smth:

function showloadingGif_UPLOAD() {
  document.getElementById('ContentPlaceHolder1_divShowLoadingGif').style.display = 'inline';
  setTimeout(function() { HideLoader(); }, DESIRED_MINIMAL_TIMEOUT);
  return true;
}
function HideLoader() {
  document.getElementById('ContentPlaceHolder1_divShowLoadingGif').style.display = 'none';
}

字符串

qxsslcnc

qxsslcnc2#

我以前也有过类似的问题,下面是我的解决方案:

<button type="button" runat="server" id="btnDownloadInfo" class="btn btn-primary downnloadReport" onserverclick="btnDownloadInfo_Click" onclick="blockUIForDownload();">Report Download</button>
<asp:HiddenField ID="HID_Reports" runat="server" />

<script type="text/javascript">
function getCookie(key) {
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
    return keyValue ? keyValue[2] : null;
}

var fileDownloadCheckTimer;

function blockUIForDownload() {
    var token = new Date().getTime(); //use the current timestamp as the token value
    $("#HID_Reports").val(token);
    showloadingGif_UPLOAD();
    fileDownloadCheckTimer = window.setInterval(function () {
        var cookieValue = getCookie('fileDownloadToken');
        if (cookieValue == token)
            finishDownload();
    }, 1000);
}

function finishDownload() {
    window.clearInterval(fileDownloadCheckTimer);
    HideLoader();
}
</script>

字符串
后面的代码:

public static void DownloadReport(DataTable dtRecord){
try
{
    string strFilename = string.Empty;

    using (XLWorkbook wb = new XLWorkbook())
    {
        CommonDB.WriteLog("Dt Count 3 : " + dtRecord.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
        wb.Worksheets.Add(dtRecord, "SheetName");
        strFilename = DateTime.Now.ToString();

        CommonDB.WriteLog("Dt Count 4 : " + dtRecord.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());

        var httpResopnse = Response;
        httpResopnse.Clear();
        httpResopnse.Buffer = true;
        httpResopnse.Charset = "";

        httpResopnse.ContentType =
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        httpResopnse.AppendCookie(new HttpCookie("fileDownloadToken", HID_Reports.Value));
        httpResopnse.AddHeader("content-disposition",
            "attachment;filename=JIO_LOS_REPORT_" + strFilename + ".xlsx"); H
        CommonDB.WriteLog("Dt Count 5 : " + dtRecord.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());

        using (MemoryStream MyMemoryStream = new MemoryStream())
        {
            CommonDB.WriteLog("Dt Count 6 : " + dtRecord.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
            wb.SaveAs(MyMemoryStream);
            MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
            CommonDB.WriteLog("Dt Count 7 : " + dtRecord.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
        }
        httpResopnse.Flush();
        httpResopnse.End();
    }
}
catch (ThreadAbortException)
{
    // Forced termination. Exit silently.
    // caused by httpResponse.End();
    // .End is needed to complete download properly ?? file is corrupt otherwise
}
catch (Exception ex)
{
    string strErrorMsg = ex.Message.ToString() + " " + "StackTrace :" + ex.StackTrace.ToString();
    CommonDB.WriteLog("ERROR:" + strErrorMsg, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
}
}


使用cookie来获取下载的显示/隐藏飞溅的天气,你用什么来显示或隐藏加载GIF替换。

相关问题