首页 > 解决方案 > 使用 Spring Boot 和 Java 脚本从应用程序下载压缩的父文件夹时出错

问题描述

我正在开发 Spring Boot 应用程序,我需要在其中提供下载压缩报告文件功能。为了做到这一点,我将压缩报告文件转换为字节数组,然后尝试在浏览器端发送它。我可以下载压缩的报告文件,但是当我尝试提取它时会显示错误消息“压缩的压缩文件夹无效。” 请在下面找到代码片段:

服务器端代码:

@ResponseBody
    @RequestMapping(value = "/downloadResult", method = RequestMethod.POST, produces="application/zip" )
    public byte[] downloadResult(@RequestBody ResultParamsVO resultParamsVO, HttpServletRequest request,
            HttpServletResponse response) {
        byte[] result = null;
        try {
            HttpSession session = request.getSession(false);

 

            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String user = auth.getPrincipal().toString();
            String testType = null;
            if (session.getAttribute("testType") != null) {
                testType = session.getAttribute("testType").toString();
            }
            result = jobService.downloadResult(resultParamsVO, testType, user);

 

            response.setStatus(HttpServletResponse.SC_OK);
            response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=resultDownload1.zip");

 

        } catch (Exception e) {
            logger.error("Error in getResult() for job id - " + resultParamsVO.getJobId(), e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

浏览器端 Ajax 调用:

$.ajax({
          type: "POST",
          url: "/downloadResult",
          contentType: "application/json",
          data: JSON.stringify(resultParamsVO),
          success: function(result) {
             
              var downloadUrl = window.URL.createObjectURL(new Blob([result], {type: "application/zip"}));
              var a = document.createElement("a");
              a.href = downloadUrl;
              a.download = "resultDownload.zip";
              document.body.appendChild(a);
              a.click();
          }
        });

请帮忙。提前致谢。

标签: ajaxspring-boot

解决方案


推荐阅读