File Download start event in Struts

后端 未结 3 1976
悲&欢浪女
悲&欢浪女 2021-01-23 03:28

In my struts application, a user can download a file from the server.

I want to show a spinner during the time between the button click (to initiate the download) and fi

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-23 03:55

    For this answer, I'll assume "plain" JSP/Servlet/HTML/JS as I don't use Struts. For an advanced Struts (and jQuery) user it should however be trivial enough to port it to Struts (and jQuery).

    To the point, you could set a cookie on the response of the download request and have JavaScript to poll for that cookie. Once the download is ready to be served, the cookie will be available in JavaScript. To ensure working across various browser windows/tabs in the same session, best is to generate an unique download token and pass it back as request parameter so that the server side can set it as a cookie value. Don't forget to expire the cookie afterwards to prevent cookie pollution.

    Basically (you could substitute the with an pointing to some spinner gif):

    
    
    

    With this JavaScript (when using jQuery, the jquery-cookie plugin may be helpful):

    function download() {
        var token = new Date().getTime();
        var wait = document.getElementById("wait");
        wait.style.display = "block";
    
        var pollDownload = setInterval(function() {
            if (document.cookie.indexOf("download=" + token) > -1) {
                document.cookie = "download=" + token + "; expires=" + new Date(0).toGMTString() + "; path=/";
                wait.style.display = "none";
                clearInterval(pollDownload);
            }
        }, 500);
    
        window.location = "download?token=" + token;
    }
    

    And in the servlet (or Struts action if applicable):

    // Prepare download here.
    // ...
    
    // Once finished, set cookie and stream download to response.
    Cookie cookie = new Cookie("download", request.getParameter("token"));
    cookie.setPath("/");
    response.addCookie(cookie);
    // ...
    

提交回复
热议问题