본문 바로가기

Spring Boot

[SpringBoot] zip파일 압축/압축해제 구현

반응형

1. Spring Boot 환경에서 zip 파일 압축을 구현하는 몇 가지 방법이 있는데, 여기에는 내장된 Java 라이브러리, 타사 라이브러리 또는 사용자 지정 코드를 사용하는 방법이 포함됩니다. 다음은 Java 기본 제공 ZipOutputStream 클래스를 사용하는 간단한 예입니다.

@RestController
public class ZipController {

    @GetMapping("/zip")
    public void downloadZip(HttpServletResponse response) throws IOException {
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=files.zip");

        try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
            addToZipFile(zos, "file1.txt", "content1".getBytes());
            addToZipFile(zos, "file2.txt", "content2".getBytes());
        }
    }

    private void addToZipFile(ZipOutputStream zos, String fileName, byte[] content) throws IOException {
        ZipEntry zipEntry = new ZipEntry(fileName);
        zos.putNextEntry(zipEntry);
        zos.write(content);
        zos.closeEntry();
    }
}

이 예에서는 RestController를 사용하여 /zip 대한 GET 요청을 처리합니다. 내용 유형을 application/zip으로 설정하고 Content-Disposition 헤더를 attachment, filename=files.zip으로 설정하여 응답이 브라우저에서 다운로드로 처리되도록 합니다. ZipOutputStream은 Zip 파일의 내용을 응답 출력 스트림에 쓰는 데 사용됩니다. addToZipFile 메서드는 개별 파일을 zip 아카이브에 추가하는 데 사용됩니다.

이것은 스프링 부트 환경에서 zip 파일 압축을 구현하는 방법의 한 가지 예에 불과합니다. 응용프로그램의 특정 요구사항에 따라 다양한 변형 및 최적화를 수행할 수 있습니다.

 

2. ava 내장 ZipInputStream 클래스를 사용하여 Spring Boot 환경에서 zip 파일 압축 해제를 구현하는 간단한 예입니다.

@RestController
public class ZipController {

    @PostMapping("/unzip")
    public void uploadAndUnzip(@RequestParam("file") MultipartFile file) throws IOException {
        try (ZipInputStream zis = new ZipInputStream(file.getInputStream())) {
            ZipEntry zipEntry = zis.getNextEntry();
            while (zipEntry != null) {
                String fileName = zipEntry.getName();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    baos.write(buffer, 0, len);
                }
                byte[] bytes = baos.toByteArray();
                // process the decompressed bytes for each file in the zip archive
                zipEntry = zis.getNextEntry();
            }
        }
    }
}

이 예에서는 Rest Controller를 사용하여 /unzip 대한 POST 요청을 처리합니다. 업로드된 zip 파일은 MultipartFile로 수신되고 uploadAndUzip 메서드로 전달됩니다. ZipInputStream은 zip 파일의 내용을 읽기 위해 생성되고 getNextEntry 메서드는 아카이브의 개별 파일을 반복하기 위해 사용됩니다. 각 파일의 내용은 압축이 해제되어 ByteArrayOutputStream에 저장됩니다. 결과 바이트 배열은 응용프로그램에서 필요에 따라 처리할 수 있습니다.

반응형