[java] Google Guice로 파일 업로드 처리하기

파일 업로드는 웹 애플리케이션에서 자주 사용되는 기능 중 하나입니다. 이번 포스트에서는 Java 언어와 Google Guice 프레임워크를 사용하여 파일 업로드를 처리하는 방법에 대해 알아보겠습니다.

1. 의존성 추가하기

먼저, Maven 또는 Gradle과 같은 빌드 도구를 사용하여 프로젝트에 아래의 의존성을 추가해야 합니다.

<dependency>
    <groupId>com.google.inject</groupId>
    <artifactId>guice</artifactId>
    <version>4.2.3</version>
</dependency>

<dependency>
    <groupId>com.google.inject.extensions</groupId>
    <artifactId>guice-servlet</artifactId>
    <version>4.2.3</version>
</dependency>

2. 파일 업로드를 처리할 모듈 생성하기

Google Guice를 사용하면 모듈을 통해 의존성 주입을 설정할 수 있습니다. 다음은 파일 업로드 처리를 위한 모듈의 예입니다.

import com.google.inject.servlet.ServletModule;
import com.google.inject.servlet.UploadModule;

public class FileUploadModule extends ServletModule {
    @Override
    protected void configureServlets() {
        install(new UploadModule());
    }
}

3. 파일 업로드 핸들러 생성하기

파일 업로드 요청을 처리하는 핸들러를 작성해야 합니다. 파일 업로드 핸들러는 HttpServlet을 상속받아 구현할 수 있습니다. 아래는 간단한 파일 업로드 핸들러의 예입니다.

import com.google.inject.Inject;
import com.google.inject.Singleton;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Singleton
public class FileUploadHandler extends HttpServlet {

    @Inject
    public FileUploadHandler() {}

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 전송된 파일 저장하기
        String fileName = req.getHeader("File-Name");
        InputStream fileContent = req.getInputStream();
        File file = new File("/path/to/save/" + fileName);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = fileContent.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, bytesRead);
        }
        fileOutputStream.close();

        resp.setStatus(HttpServletResponse.SC_OK);
        resp.getWriter().println("File uploaded successfully");
    }
}

4. 모듈 등록하기

마지막으로, 생성한 모듈과 핸들러를 Guice에 등록하여 사용할 수 있도록 설정해야 합니다. 아래 예제는 Guice의 ServletContextListener를 사용하여 모듈과 핸들러를 설정하는 방법입니다.

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;

public class MyServletContextListener extends GuiceServletContextListener {
    @Override
    protected Injector getInjector() {
        return Guice.createInjector(new FileUploadModule());
    }
}

결론

Google Guice 프레임워크를 사용하면 Java로 파일 업로드를 간편하게 처리할 수 있습니다. 위의 코드와 단계를 따라해보면 파일 업로드 기능을 가진 웹 애플리케이션을 구현할 수 있을 것입니다.

참고: Google Guice