简体   繁体   English

文件下载后重新加载页面

[英]Make page reload after file download

I am delivering a jasper report as a PDF for download.我正在提供一份碧玉报告作为 PDF 供下载。 But when I do it I become unable to make the page to reload or redirect.但是当我这样做时,我无法使页面重新加载或重定向。

The page that causes the download to take place uses a form submission to start the file download.导致下载发生的页面使用表单提交来开始文件下载。 The answer provided by Govinda Sakhare was posted before I made this clarification. Govinda Sakare 提供的答案是在我做出澄清之前发布的。 However his answer could be implemented with little work as the form only has one choice (big or small).然而,他的答案可以通过很少的工作来实现,因为表单只有一个选择(大或小)。

The function that handles the server response is below:处理服务器响应的 function 如下:

    private void generateReportPDF(JasperReport jasperReport, List<? extends Object> data, Map<String, Object> parameters, HttpServletResponse resp) throws Exception {
        byte[] bytes = null;
        if( data == null ) {
            bytes = JasperRunManager.runReportToPdf(jasperReport, parameters, reportDao.getConnection());
        }
        else {
            bytes = JasperRunManager.runReportToPdf(jasperReport, parameters, new JRBeanCollectionDataSource(data));
        }
        resp.reset();
        resp.resetBuffer();
        resp.setContentType("application/pdf");
        resp.addHeader("Content-Disposition", "attachment; filename=" + jasperReport.getName() + ".pdf");
        resp.setContentLength(bytes.length);

        ServletOutputStream ouputStream = resp.getOutputStream();

        ouputStream.write(bytes, 0, bytes.length);
        ouputStream.flush();
        ouputStream.close();
        return;
    }

Because of this function, my controller is unable to redirect the page and I get the following error when I try to.由于这个 function,我的 controller 无法重定向页面,当我尝试重定向时出现以下错误。

SEVERE: Servlet.service() for servlet [myapp-dispatcher] in context with path [/myapp] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed] with root cause
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

I want to reload the page.我想重新加载页面。 This is on a label printing screen and after the file download, I want the page to reload/redirect to itself so that labels which were printed are displayed in their new spot.这是在 label 打印屏幕上,文件下载后,我希望页面重新加载/重定向到自身,以便打印的标签显示在新位置。 Since the controller is unable to redirect, I have to modify the original process which is handling the response or implement JavaScript to occur after the file has been dealt with.由于 controller 无法重定向,我必须修改处理响应的原始进程或在文件处理后执行 JavaScript。

This question asks about catching downloads and responding to them, but does not involve spring so the answers would require more changes than I want to make.这个问题询问有关捕获下载和响应它们的问题,但不涉及 spring 所以答案需要比我想做的更多的更改。

Using one of the answers from the question I managed to make a workaround but its not satisfactory to me.使用问题中的一个答案,我设法解决了问题,但对我来说并不满意。

 $(document).ready(function() {
        $('#printBtn').click(function() {


            if(confirm('<spring:message code="print.alert.confirm"/>') ? true : false)
                {
                    window.addEventListener('focus', window_focus, false);
                     function window_focus(){
                        //remove buttons
                        var elem1 = document.getElementById('printBtn');
                        elem1.parentNode.removeChild(elem1);
                        //elem1.parentNode.replaceChild(newbutton);
                        var elem2 = document.getElementById('clearBtn');
                        elem2.parentNode.removeChild(elem2);
                        var elem3 = document.getElementById('restoreBtn');
                        elem3.parentNode.removeChild(elem3);
                        document.getElementById('button_spot').innerHTML = "The page will reload after you get the file.";

                        //watch for page to lose focus due to download dialog box
                        window.addEventListener('focusout', pageNoFocus);
                        function pageNoFocus(){
                            //watch for page to resume focus
                            window.removeEventListener('focusout', pageNoFocus);
                            window.addEventListener('focus', pageFocus);
                            function pageFocus(){
                                window.removeEventListener('focus', pageFocus);
                                location.reload();
                            }
                        }
                    }

                    return true;
                }
            return false;


        });

        $('#clearBtn').click(function() {
            return confirm('<spring:message code="print.alert.clear"/>') ? true : false;
        });

        $('#restoreBtn').click(function() {
            return confirm('<spring:message code="print.alert.restore"/>') ? true : false;
        });
    });

You can use the following snippet to download the file and redirect to some URL.您可以使用以下代码段下载文件并重定向到某些 URL。

<a href="#" id="download">Download</a>
<a href="downloadfileURL" target="_blank" id="downloadFile" /> 
<!-- change href with Spring mapping which will download the file -->

On click of Download link, it will click anchor which points to the actual URL.单击下载链接时,它将单击指向实际 URL 的锚点。
The file will be downloaded, followed by that it will redirect to the window.location.href该文件将被下载,然后它将重定向到window.location.href

$("#download").click(function () {
   $("#downloadFile")[0].click();
   window.location.href = "/abc.html"; // change to the desired URL
});

If you download the file via form submission use below snippet.如果您通过表单提交下载文件,请使用以下代码段。

$("#formId").click(function (e) {
   e.preventDefault();
   $("#downloadFile")[0].click();
   window.location.href = "/abc.html"; // change to the desired URL
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM