스프링부트에서 @Controller로 이미지 파일을 업로드하고 관리하는 방법을 알려줘
- User
스프링부트에서 @Controller로 이미지 파일을 업로드하고 관리하는 방법을 알려줘
- Assistant
스프링부트에서 @Controller로 이미지 파일을 업로드하고 관리하는 방법을 알려줘
스프링 부트에서는 이미지 파일을 업로드하고 관리하는 방법은 비교적 간단합니다. 다음 예제를 통해 @Controller를 이용해 이미지 파일을 저장하고 관리하는 방법을 설명하겠습니다. 이 예제에서는 이미지 파일을 로컬 디스크에 저장하는 방식을 사용하지만, 실제 애플리케이션 환경에서는 파일 스토리지 서비스(AWS S3 등)를 활용하는 것도 좋습니다.
spring-boot-starter-web 의존성을 포함하는 build.gradle 또는 pom.xml 설정 파일을 업데이트합니다.
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
}
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
이미지를 저장할 로컬 디렉토리를 지정합니다. 예를 들어, images라는 디렉토리를 사용할 수 있습니다.
다음은 이미지 파일을 업로드하고, 저장할 파일을 관리하는 Controller 클래스 예제입니다.
package com.example.demo.controller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller
public class ImageUploadController {
// 이미지를 저장할 디렉토리 경로
private static String UPLOADED_FOLDER = "images/";
@GetMapping("/")
public String index() {
return "upload"; // upload.html view를 반환
}
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
try {
// 파일을 지정된 위치에 저장
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/uploadStatus";
}
@GetMapping("/uploadStatus")
public String uploadStatus() {
return "uploadStatus";
}
@GetMapping("/image/{filename}")
@ResponseBody
public ResponseEntity<byte[]> getImage(@PathVariable("filename") String filename) {
try {
Path path = Paths.get(UPLOADED_FOLDER + filename);
byte[] imageBytes = Files.readAllBytes(path);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}
이미지 업로드를 위한 HTML 폼과 업로드 상태를 확인할 수 있는 HTML 파일을 작성합니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Form</title>
</head>
<body>
<h1>Image Upload</h1>
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file"/>
<button type="submit">Upload</button>
</form>
<div>
<h2>Status</h2>
<p th:text="${message}"></p>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Status</title>
</head>
<body>
<h1>Upload Status</h1>
<p th:text="${message}"></p>
</body>
</html>
스프링부트 애플리케이션을 실행하고, 브라우저에서 http://localhost:8080 으로 접속하여 이미지 업로드 기능을 테스트합니다. 이미지를 업로드한 후 http://localhost:8080/image/your_uploaded_file_name.jpg 경로로 저장된 이미지를 확인할 수 있습니다.
이렇게 하면 스프링부트 애플리케이션에서 이미지 업로드 및 관리를 효과적으로 할 수 있습니다. 필요에 따라 유효성 검사, 예외 처리, 보안 설정 등을 추가할 수 있습니다.
Not yet included in a published release.