代码之家  ›  专栏  ›  技术社区  ›  Dolphin

无法打开从服务器下载的zip文件

  •  0
  • Dolphin  · 技术社区  · 3 年前

    我使用这个java(版本11)函数在Spring Boot中从服务器端下载zip文件( v2.6.7 ):

    public void downloadPhotoBatchTest() throws IOException {
            ZipFile zipFile = new ZipFile(new File("/Users/john/59c49360-3b55-4f97-910e-9f33907f10cb.zip"));
            httpResponse.setContentType("application/zip");
            httpResponse.setHeader("Content-Disposition", "attachment; filename=\"" + zipFile.getName() + "\"");
            httpResponse.setHeader("Content-Length", String.valueOf(zipFile.size()));
            try (OutputStream out = httpResponse.getOutputStream();
                 FileInputStream in = new FileInputStream("/Users/john/59c49360-3b55-4f97-910e-9f33907f10cb.zip")) {
                byte[] buffer = new byte[4096];
                int length;
                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                }
                out.flush();
            } catch (IOException e) {
                log.error("write zip to response error", e);
            }
        }
    

    但现在我发现zip文件的大小与服务器端不一样,下载的文件只有2KB,而且下载的文件无法打开。我是不是在这个代码中遗漏了什么,我读了代码,但找不到导致这个问题的原因。我该怎么办才能解决这个问题?这是httpResponse定义:

    @Autowired
    private HttpServletResponse httpResponse;
    
    1 回复  |  直到 3 年前
        1
  •  2
  •   Codo    3 年前

    除了内容类型之外,您的代码不需要关心它是zip文件还是其他文件类型。它只需要传输文件。

    特别是,不要使用 ZipFile.size() 对于 Content-Length ZipFile.size() 返回zip文件中的文件数,而 内容长度 应为字节数。

    你没有具体说明什么 httpResponse 是和从哪里来的。而且它看起来不像惯用的Spring Boot。更好的Spring Boot代码是:

    @RequestMapping("/photoBatch")
    public ResponseEntity<InputStreamResource> downloadPhotoBatch() throws IOException {
    
        File file = new File("/Users/john/59c49360-3b55-4f97-910e-9f33907f10cb.zip");
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
    
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
                .contentType(MediaType.parseMediaType("application/zip")
                .contentLength(file.length())
                .body(resource);
    }
    
    推荐文章