스프링부트에서 @Controller를 사용하여 이미지 파일을 업로드하고 관리하려면 다음과 같은 단계를 따르면 됩니다. 여기서는 기본적인 파일 업로드, 저장, 조회를 위한 예제를 제공합니다.
1. 프로젝트 설정
먼저, spring-boot-starter-thymeleaf와 spring-boot-starter-web 의존성을 포함한 Spring Boot 프로젝트를 생성합니다. pom.xml에 필요한 의존성을 추가하세요.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
2. 파일 업로드를 위한 Controller 작성
이미지 파일을 업로드하고 관리하기 위한 컨트롤러를 생성합니다.
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
public class ImageController {
private static final String UPLOAD_DIR = "uploads/";
@GetMapping("/")
public String index() {
return "index";
}
@PostMapping("/upload")
public String uploadImage(@RequestParam("image") MultipartFile file, Model model) {
if (file.isEmpty()) {
model.addAttribute("message", "Please select a file to upload");
return "index";
}
try {
String uploadPath = UPLOAD_DIR + file.getOriginalFilename();
file.transferTo(new File(uploadPath));
model.addAttribute("message", "File uploaded successfully: " + file.getOriginalFilename());
} catch (IOException e) {
e.printStackTrace();
model.addAttribute("message", "Failed to upload file: " + file.getOriginalFilename());
}
return "index";
}
}
3. view 작성 (Thymeleaf 사용)
업로드 폼을 구성하는 Thymeleaf 템플릿 파일을 작성합니다.
src/main/resources/templates/index.html 파일을 생성하고 다음 내용을 추가하세요.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Image Upload</title>
</head>
<body>
<h1>Image Upload Form</h1>
<div th:if="${message}" th:text="${message}"></div>
<form method="post" enctype="multipart/form-data" action="/upload">
<label for="file">Select an image:</label>
<input type="file" id="file" name="image" accept="image/*">
<button type="submit">Upload</button>
</form>
</body>
</html>
4. application.properties 설정
업로드된 파일이 저장되는 디렉토리를 설정합니다. 일반적으로 /tmp 디렉토리를 사용하는 것이 가장 간단하지만, 실제 애플리케이션에서는 적절한 디렉토리를 지정하세요.
spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=2MB
또한, uploads 디렉토리를 프로젝트 루트에 생성해 주세요.
5. 실행하고 테스트하기
이제 애플리케이션을 실행하고 웹 브라우저에서 http://localhost:8080으로 접속하여 이미지를 업로드할 수 있습니다.
이 기본 예제를 통해 스프링부트에서 @Controller를 사용하여 이미지 파일을 업로드하고 관리하는 방법을 배웠습니다. 실제로는 파일 URI를 데이터베이스에 저장하거나 더 다양한 예외 처리를 추가하여 기능을 확장할 수 있습니다.