这可能是一个非常简单的问题,但实际上我没有看到很多搜索结果。
我在表单中有一个非常基本的提交按钮,它接受一些用户输入,并在服务器的临时目录中生成可下载的文件,然后提示用户下载此文件,然后在提交时禁用该文件:
<form action="Home" method="post" onsubmit="Submit.disabled = true; return true;">
...
<input type="submit" name="Submit" value="Submit" id="Submit" />
我们需要在页面创建文件时禁用它几秒钟,然后提示用户下载它。创建文件后,它会在SelectionServlet.java中返回以下响应,以便浏览器可以下载生成的文件,例如:
if (Export.equals("PDF")){
response.setContentType(".pdf");
response.setHeader("Content-disposition", "attachment; filename="+Constants.FILE_NAME+".pdf");
File dlFile = new File(Constants.FILE_LOCATION+".pdf");
// This should send the file to browser
OutputStream outStream = response.getOutputStream();
FileInputStream in = new FileInputStream(dlFile);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
in.close();
outStream.flush();
Export="HTML";
}
文件准备下载后,我想重新启用“提交”按钮,以便用户可以重新使用他们放入的表单数据(没有完成页面重定向,因为用户基本上只选择了什么标准进入他们正在构建的文件,它是什么文件类型,提交按钮最终将我们带到一个连接到源的java Web连接,并将各种文件类型构建到服务器的临时目录中,以便通过用户)。
我在Chrome中玩过,我实际上可以在提交按钮上删除已禁用的属性,然后再次单击该按钮,但使用不同的条件并获得不同的结果。什么代码实际上可以做到这一点,我不确定。
答案 0 :(得分:5)
在文件下载的响应上设置cookie,让JavaScript按时间间隔检查cookie。一旦文件下载准备好提供,因此另存为对话框正在发生,那么cookie将可供JavaScript使用。为了确保在同一会话中跨多个浏览器窗口/选项卡正常工作,最好是在JavaScript中生成一个唯一令牌,将其作为请求参数传递给下载请求,并让servlet将其设置为cookie值。
基本上,这应该做:
<form action="Home" method="post" onsubmit="startDownload(this)">
...
<input type="hidden" name="token" />
<input type="submit" name="Submit" value="Submit" id="Submit" /> <!-- I'd rather rename and lowercase the ID/name. -->
</form>
使用此JavaScript(使用jQuery时,jquery-cookie plugin可能有助于减少document.cookie
详细程度:
function startDownload(form) {
var token = new Date().getTime();
form.token.value = token;
form.Submit.disabled = true;
var pollDownload = setInterval(function() {
if (document.cookie.indexOf("download=" + token) > -1) {
document.cookie = "download=" + token + "; expires=" + new Date(0).toGMTString() + "; path=/";
form.Submit.disabled = false;
clearInterval(pollDownload);
}
}, 500);
}
在servlet中:
// Prepare download here.
// ...
// Once finished preparing, set cookie.
Cookie cookie = new Cookie("download", request.getParameter("token"));
cookie.setPath("/");
response.addCookie(cookie);
// Now stream download to response.
// ...