將多個檔案壓縮成zip檔案進行下載

kay發表於2017-02-18
@GetMapping("/download/zip")
    public void downloadZipFile(HttpServletResponse response) throws IOException {

        response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
        response.setHeader("Content-Disposition","attachment; filename="images.zip"");

        List<String> fileNames = Arrays.asList("1.jpg","2.jpg","3.jpg");
        ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());

        for(String fileName : fileNames) {
            ZipEntry zipEntry = new ZipEntry(fileName);
            zipOutputStream.putNextEntry(zipEntry);
            FileInputStream inputStream = new FileInputStream("D:/upload/"+fileName);
            IOUtils.copy(inputStream,zipOutputStream);
            inputStream.close();
        }

        zipOutputStream.closeEntry();
        zipOutputStream.close();
    }

相關文章