[java] Thymeleaf에서 멀티파트 파일 업로드를 어떻게 처리하나요?

Thymeleaf에서 멀티파트 파일 업로드 처리하기

Thymeleaf는 서버측 Java 템플릿 엔진이며, 멀티파트 파일 업로드를 처리하는 데에도 사용할 수 있습니다. 이번 포스트에서는 Thymeleaf를 사용하여 멀티파트 파일 업로드를 처리하는 방법에 대해 알아보겠습니다.

1. HTML Form 생성하기

먼저, 멀티파트 파일 업로드를 위한 HTML Form을 생성해야 합니다. 다음과 같이 HTML Form을 작성합니다.

<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <button type="submit">Upload</button>
</form>

위의 코드에서 enctype 속성은 multipart/form-data로 설정해야 멀티파트 파일을 서버로 전송할 수 있습니다. input 태그의 name 속성은 서버에서 파일을 식별하기 위해 사용됩니다.

2. Controller 작성하기

다음으로, 멀티파트 파일 업로드를 처리할 Controller를 작성해야 합니다. 다음은 Spring MVC를 기반으로 한 Controller의 예시입니다.

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UploadController {

    @PostMapping("/upload")
    public String handleUpload(MultipartFile file) {
        // 파일 업로드 처리 로직 작성
        // 파일 정보는 MultipartFile 객체를 통해 접근할 수 있습니다.
        return "File uploaded successfully!";
    }
}

위의 코드에서 handleUpload 메소드는 MultipartFile 객체를 파라미터로 받아와 파일 업로드를 처리합니다. 업로드된 파일에 접근하기 위해 MultipartFile 객체를 사용할 수 있습니다.

3. 파일 업로드 처리 로직 작성하기

마지막으로, 파일 업로드 처리 로직을 작성해야 합니다. 이 부분은 개발자에게 달려있는 부분이므로, 필요한 로직을 작성하시면 됩니다. 예를 들어, 업로드된 파일을 저장하거나 파일의 내용을 읽어오는 등의 작업을 수행할 수 있습니다.

주의할 점은, 업로드된 파일은 보안상의 이유로 임시 디렉토리에 저장되므로, 최종적으로는 안전한 위치에 저장해야 한다는 것입니다.

결론

Thymeleaf를 사용하여 멀티파트 파일 업로드를 처리하는 방법에 대해 알아보았습니다. 위의 단계를 따라서 진행하면 멀티파트 파일 업로드를 쉽게 구현할 수 있습니다.