[java] Java Jersey에서 파일 다운로드 처리하는 방법은?

Java Jersey를 사용하여 파일 다운로드를 처리하는 방법에 대해 알아보겠습니다.

먼저, 클라이언트에서 다운로드 요청을 받은 후, 서버에서 파일을 읽어와 클라이언트로 전송해야 합니다. 이를 위해 다음과 같은 단계를 따를 수 있습니다.

  1. 다운로드 요청 처리를 위한 엔드포인트(Route)를 정의합니다. Jersey에서는 @GET 어노테이션과 @Path 어노테이션을 사용하여 엔드포인트를 정의할 수 있습니다. 예를 들어, 파일 다운로드를 위한 엔드포인트 경로를 “/download/{filename}”으로 설정할 수 있습니다.
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import java.io.File;

@Path("/download")
public class FileDownloadResource {

    @GET
    @Path("/{filename}")
    public Response downloadFile(@PathParam("filename") String filename) {
        // 파일 다운로드 처리 로직 작성
        File file = new File(filename);
        
        // 파일이 존재하는지 확인한 후, 있다면 Response에 파일 데이터를 첨부하여 전송
        if (file.exists()) {
            return Response.ok(file)
                           .header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"")
                           .build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }

}
  1. 다운로드 요청을 정상적으로 처리하기 위해 필요한 라이브러리를 추가하고 파일 경로를 설정합니다.
<dependencies>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-multipart</artifactId>
    </dependency>
</dependencies>
  1. 파일 다운로드 요청을 보내고 파일을 받아옵니다. 예를 들어, 웹 브라우저에서 “/download/example.pdf”에 요청을 보내면, 서버에서 “example.pdf” 파일을 찾아서 다운로드 받을 수 있습니다.
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class FileDownloader {

    public static void main(String[] args) throws IOException {
        String fileUrl = "http://your-server-url/download/example.pdf";
        String savePath = "/path/to/save/downloaded/file/example.pdf";

        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        try (InputStream in = connection.getInputStream()) {
            Path outputPath = Paths.get(savePath);
            Files.copy(in, outputPath, StandardCopyOption.REPLACE_EXISTING);
        }
    }

}

이렇게 Java Jersey를 사용하여 파일 다운로드를 처리할 수 있습니다. 파일 다운로드를 위한 엔드포인트를 정의하고, 클라이언트에서 요청을 보내면 서버에서 파일을 찾아서 전송하는 방식입니다. 적절한 경로와 파일명을 설정하여 파일을 다운로드 받을 수 있습니다.