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

aoh*_*989 1 javascript java forms servlets download

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

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

<form action="Home" method="post" onsubmit="Submit.disabled = true; return true;">
...
<input type="submit" name="Submit" value="Submit" id="Submit" />
Run Code Online (Sandbox Code Playgroud)

我们需要在页面创建文件时禁用它几秒钟,然后提示用户下载它.创建文件后,它会在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";
            }
Run Code Online (Sandbox Code Playgroud)

准备好下载文件后,我想重新启用"提交"按钮,以便用户可以重新使用他们放入的表单数据(没有进行页面重定向,因为用户基本上只选择了什么标准进入他们正在构建的文件,以及它的文件类型,Submit按钮最终将我们带到一个连接到源的java Web连接,并将各种文件类型构建到服务器的temp目录中,以供用户下载) .

我在Chrome中玩过,我实际上可以在提交按钮上删除已禁用的属性,然后再次单击该按钮但使用不同的条件并获得不同的结果.什么代码实际上可以做到这一点,我不确定.

Bal*_*usC 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>
Run Code Online (Sandbox Code Playgroud)

使用这个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);
}
Run Code Online (Sandbox Code Playgroud)

在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.
// ...
Run Code Online (Sandbox Code Playgroud)