[java] RESTful 웹 서비스에서 파일 다운로드 방법

RESTful 웹 서비스에서 클라이언트가 서버에서 파일을 다운로드하는 방법에 대해 설명하겠다.

1. HTTP GET 메서드 이용

클라이언트는 HTTP GET 요청을 사용하여 서버로 파일을 요청한다. 서버는 해당 파일을 바이트 단위로 스트림을 생성 후, 클라이언트로 전송한다. 이때, Content-Disposition 헤더를 사용하여 파일 이름과 함께 전송할 수 있다.

예시:

@Path("/file")
@Produces("application/octet-stream")
public Response downloadFile() {
    File file = new File("/path/to/file.pdf");
    if (!file.exists()) {
        throw new WebApplicationException(404);
    }
    return Response.ok(file, "application/octet-stream")
                   .header("Content-Disposition", "attachment; filename=\"file.pdf\"")
                   .build();
}

2. 파일 다운로드 경로 설정

서버 측에서 RESTful API로 파일 다운로드를 제공하기 위해, 파일이 저장된 경로에 대한 설정이 필요하다. 이때는 업로드된 파일의 경로를 알맞게 설정하고, 해당 경로를 클라이언트에게 제공하면 된다.

예시:

@Path("/file")
public class FileResource {
    private static final String FILE_PATH = "/path/to/file.pdf";

    @GET
    @Produces("application/octet-stream")
    public Response downloadFile() {
        File file = new File(FILE_PATH);
        if (!file.exists()) {
            throw new WebApplicationException(404);
        }
        return Response.ok(file, "application/octet-stream")
                   .header("Content-Disposition", "attachment; filename=\"file.pdf\"")
                   .build();
    }
}

요약

이러한 방법을 통해, RESTful 웹 서비스를 통해 클라이언트가 서버로부터 파일을 다운로드할 수 있다. 위에서 설명한 방법을 참고하여, 파일 다운로드에 필요한 HTTP 요청 및 파일 경로 설정을 구현해보자.

이상으로 RESTful 웹 서비스에서 파일 다운로드하는 방법에 대한 설명을 마친다.

참고 문헌