在响应文件下载时重新启用表单提交按钮
Reenable a form submit button on response of a file download
这可能是一个非常简单的问题,但我实际上没有看到很多关于这个问题的搜索结果。
我在表单中有一个非常基本的提交按钮,该按钮接受一些用户输入,并在服务器的临时目录中生成一个可下载的文件,然后提示用户下载此文件,然后在提交时将其禁用:
<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";
}
文件准备好下载后,我想重新启用该"提交"按钮,以便用户可以重复使用他们输入的表单数据(没有进行页面重定向,因为用户基本上只是选择他们正在构建的文件的条件,以及文件类型,提交按钮最终将我们带到连接到源并将各种文件类型构建到用户要下载的服务器的温度目录(。
我在Chrome中玩过,我实际上可以删除提交按钮上的禁用属性,然后再次单击该按钮,但使用不同的条件并返回不同的结果。我不确定什么代码实际上可以做到这一点。
在文件下载的响应上设置一个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插件可能有助于减少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.
// ...
- HTML表单提交时未执行外部函数
- JS表单提交"无法使用Chrome数据保护程序加载此页面.尝试重新加载页面.调试信息:POST CISmtuK
- 将图像上传ajax与表单提交ajax相结合
- Javascript无法处理表单提交
- 如何在我的情况下禁用表单提交
- 加载后的页面与ajax表单提交不起作用
- angularjs-控制器在表单提交时未调用
- 禁用带有字符白名单的表单提交
- 如何使用Google Analytics跟踪表单提交
- 使用javascript将表单提交到iframe目标中
- 禁用和重新启用表单 在 Rails 中使用 JQuery 提交
- 在响应文件下载时重新启用表单提交按钮
- 如何在ajax请求中禁用/启用表单提交
- 如果表单提交失败,请启用提交按钮
- 当在asp.net web应用程序中单击启用了onserverclick的html按钮时,停止表单提交
- 防止默认的表单提交事件从触发,如果javascript使用jquery启用
- 创建一个表单提交按钮,启用“在新窗中打开”;当用户右键点击时
- 在启用表单提交之前,强制用户填写所有字段
- 在表单提交后启用文本框和按钮.Net MVC 4
- 如何在启用和禁用表单提交之间切换