如何修复java下载按钮连续单击ClientAbortException:java.io.IOException错误?

时间:2018-08-10 08:31:33

标签: java spring

我的下载页面有两个下载(pdf和安装程序)按钮。仅单击一次下载按钮时,它工作正常。但是,连续单击它会引发ClientAbortException:java.io.IOException错误。我已经找到了许多ClientAbortException答案,但对我来说它们并不容易理解。有人可以帮我解决这个错误吗?

这是我在Controller中下载按钮的代码:

@Repository    
public interface UserRepository extends JpaRepository<User, Long> {
    User findByToken(String token);
}

@Controller
public class UserController {
    @RequestMapping(value = "download", method = RequestMethod.POST, params = "action=ins")
    public String downloadInstaller(HttpServletRequest request, HttpServletResponse response, @ModelAttribute User user, Model model)
            {

        User user2 = userRepository.findByToken(user.getToken());
        if(user2.getDownload() == 0) {
            user2.setDownload(1);
            userRepository.save(user2);

            File file = new File("File");
            download(file, response);
            log.info(Log.LOG_DOWNLOAD_INSTALLER);
            return "";
        }
        return "downloaded";
    }

    @RequestMapping(value = "download", method = RequestMethod.POST, params = "action=pdf")
    public String downloadPDF(HttpServletResponse response, @ModelAttribute User user, Model model) {       
        User user2 = userRepository.findByToken(user.getToken());
        if(user2.getDownload() == 0) {
            user2.setDownload(1);
            userRepository.save(user2);
            File file = new File("Pdf");
            download(file, response);
            log.info(Log.LOG_DOWNLOAD_PDF);
            return "";
        }
        return "downloaded";
    }

    public void download(File file, HttpServletResponse response) {

        try {
            InputStream is = new FileInputStream(file);
            response.setContentType("application/octet-stream");
            // Response header
            response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
            // Read from the file and write into the response
            OutputStream os = response.getOutputStream();

            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
            os.close();
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {           
            e.printStackTrace();
        }   
    }
}

1 个答案:

答案 0 :(得分:1)

您是否从“ os.flush();”获得异常? download()方法的代码行?如果是这样,则基本上意味着发送请求的客户端不再等待响应。如果您提出了两个请求,则第一个请求可能会失败。

如果您没有想要通过多次单击按钮来实现的特殊要求,我想您可以捕获并忽略download()中的异常吗?