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

后端 未结 4 978
借酒劲吻你
借酒劲吻你 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:22

    @RequestMapping(value="/zip", produces="application/zip")
    public void zipFiles(HttpServletResponse response) throws IOException {
    
        //setting headers  
        response.setStatus(HttpServletResponse.SC_OK);
        response.addHeader("Content-Disposition", "attachment; filename=\"test.zip\"");
    
        ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
    
        // 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();
    }
    

提交回复
热议问题