在响应文件下载时重新启用表单提交按钮

Reenable a form submit button on response of a file download

本文关键字:启用 表单提交 按钮 新启用 响应 文件下载      更新时间:2023-09-26

这可能是一个非常简单的问题,但我实际上没有看到很多关于这个问题的搜索结果。

我在表单中有一个非常基本的提交按钮,该按钮接受一些用户输入,并在服务器的临时目录中生成一个可下载的文件,然后提示用户下载此文件,然后在提交时将其禁用:

<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.
// ...