在我的 struts 应用程序中,用户可以从服务器下载文件。
我想在单击按钮(启动下载)和文件准备下载之间的时间内显示一个微调器。文件开始下载时是否会触发一个事件?我认为这将是某种页面加载事件。
这是我的 struts xml 中的部分:
<action name="getFile" method="getFile" class="foo.pack.TAction">
<result name="success" type="stream">
<param name="contentType">application/pdf</param>
<param name="contentDisposition">attachment;filename=${fileName}</param>
</result>
<result name="login" type="redirect">/login</result>
<result name="error" type="tiles">showError</result>
</action>
单击按钮时,我设置window.location = localhost:8080/getFile.action
接下来下载文件(n 秒后)
在从服务器获取文件期间显示旋转器的方法是什么?
最佳答案
对于这个答案,我将假设“普通”JSP/Servlet/HTML/JS,因为我不使用 Struts。然而,对于高级 Struts(和 jQuery)用户来说,将其移植到 Struts(和 jQuery)应该很简单。
到目前为止,您可以在下载请求的响应上设置 cookie,并让 JavaScript 轮询该 cookie。一旦准备好提供下载,cookie 将在 JavaScript 中可用。为了确保在同一 session 中跨不同浏览器窗口/选项卡工作,最好是生成唯一的下载 token 并将其作为请求参数传回,以便服务器端可以将其设置为 cookie 值。不要忘记事后使 cookie 过期,以防止 cookie 污染。
基本上(您可以用指向某个旋转器 gif 的 <span>
替换 <img>
):
<input type="button" value="Download" onclick="download()" />
<span id="wait" style="display:none">Please wait while we prepare the download...</span>
使用此 JavaScript(使用 jQuery 时,jquery-cookie plugin 可能会有所帮助):
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;
}
并在 servlet(或 Struts 操作,如果适用)中:
// 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);
// ...
关于java - Struts 中的文件下载开始事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11120121/