> uploadProfileImage(
@RequestParam("file") MultipartFile file) {
try {
// 파일 저장 경로 설정
String uploadDir = "uploads/profile-images/";
String originalFilename = file.getOriginalFilename();
String newFileName = UUID.randomUUID() + "_" + originalFilename;
Path savePath = Paths.get(uploadDir + newFileName);
// 디렉토리가 없으면 생성
Files.createDirectories(savePath.getParent());
Files.copy(file.getInputStream(), savePath, StandardCopyOption.REPLACE_EXISTING);
// 저장된 파일 URL 생성 (예: http://localhost:8080/images/...)
String fileUrl = "http://localhost:8080/images/profile-images/" + newFileName;
// 응답에 URL 포함
Map 예시//이미지 업로드
@PostMapping("/upload/image")
public ResponseEntity<Map<String, String>> uploadProfileImage(
@RequestParam("file") MultipartFile file) {
try {
// 파일 저장 경로 설정
String uploadDir = "uploads/profile-images/";
String originalFilename = file.getOriginalFilename();
String newFileName = UUID.randomUUID() + "_" + originalFilename;
Path savePath = Paths.get(uploadDir + newFileName);
// 디렉토리가 없으면 생성
Files.createDirectories(savePath.getParent());
Files.copy(file.getInputStream(), savePath, StandardCopyOption.REPLACE_EXISTING);
// 저장된 파일 URL 생성 (예: <http://localhost:8080/images/>...)
String fileUrl = "<http://localhost:8080/images/profile-images/>" + newFileName;
// 응답에 URL 포함
Map<String, String> response = new HashMap<>();
response.put("url", fileUrl);
return ResponseEntity.ok(response);
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
URL을 만드는 이유
<img src="<http://localhost:8080/images/profile-images/UUID_filename.jpg>" />
URL로 접근 가능하게 하는 법
uploads/
디렉토리를 정적 자원(static resource)으로 등록해야 함application.properties
설정 추가spring.web.resources.static-locations=classpath:/static/,file:uploads/
uploads/
폴더가 정적 리소스 경로로 설정 됨localhost:8080/images/...
로 접근되게 하려면, 매핑 경로도 수정해야 됨import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**") // 요청 경로
.addResourceLocations("file:uploads/profile-images/"); // 실제 파일 경로
}
}
이렇게 하면
http://localhost:8080/images/profile-images/uuid_파일명.jpg
로 접속하면