Spring REST - create .zip file and send it to the client

后端 未结 4 993
借酒劲吻你
借酒劲吻你 2020-12-04 21:25

I want to create .zip file that contains my zipped files that I recieve from backend, and then send this file to the user. For 2 days I have been looking for the answer and

4条回答
  •  误落风尘
    2020-12-04 22:26

    @RequestMapping(value="/zip", produces="application/zip")
    public ResponseEntity zipFiles() {
        return ResponseEntity
                .ok()
                .header("Content-Disposition", "attachment; filename=\"test.zip\"")
                .body(out -> {
                    var zipOutputStream = new ZipOutputStream(out);
    
                    // create a list to add files to be zipped
                    ArrayList files = new ArrayList<>(2);
                    files.add(new File("README.md"));
    
                    // package files
                    for (File file : files) {
                        //new zip entry and copying inputstream with file to zipOutputStream, after all closing streams
                        zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
                        FileInputStream fileInputStream = new FileInputStream(file);
    
                        IOUtils.copy(fileInputStream, zipOutputStream);
    
                        fileInputStream.close();
                        zipOutputStream.closeEntry();
                    }
    
                    zipOutputStream.close();
                });
    }
    

提交回复
热议问题