44import org .springframework .stereotype .Service ;
55import org .springframework .web .multipart .MultipartFile ;
66
7+ import jakarta .annotation .PostConstruct ;
78import java .io .File ;
89import java .io .IOException ;
10+ import java .nio .file .Files ;
11+ import java .nio .file .Paths ;
912import java .util .ArrayList ;
1013import java .util .List ;
1114import java .util .UUID ;
1417@ RequiredArgsConstructor
1518public class NewsImageService {
1619
17- private static final String IMAGE_DIR = "src/main/resources/static/images/" ;
20+ // 애플리케이션 실행 경로 기반으로 이미지 저장
21+ private static final String IMAGE_DIR = System .getProperty ("user.dir" ) + "/uploaded-images/" ;
1822
19- public List <String > uploadImages (List <MultipartFile > images ) {
23+ // 애플리케이션 실행 시 이미지 폴더 미리 생성
24+ @ PostConstruct
25+ public void init () {
26+ File uploadDir = new File (IMAGE_DIR );
27+ if (!uploadDir .exists ()) {
28+ boolean isCreated = uploadDir .mkdirs ();
29+ if (isCreated ) {
30+ System .out .println ("이미지 저장 폴더 생성됨: " + IMAGE_DIR );
31+ } else {
32+ System .err .println ("이미지 저장 폴더 생성 실패함......." );
33+ }
34+ }
35+ }
2036
37+ public List <String > uploadImages (List <MultipartFile > images ) {
2138 List <String > imageUrls = new ArrayList <>();
2239
2340 if (images != null ) {
@@ -26,27 +43,32 @@ public List<String> uploadImages(List<MultipartFile> images) {
2643 String imageUrl = saveImage (image );
2744 imageUrls .add (imageUrl );
2845 } catch (IOException e ) {
29- throw new RuntimeException ("이미지 저장 중 오류" , e );
46+ e .printStackTrace ();
47+ throw new RuntimeException ("이미지 저장 중 오류: " + e .getMessage (), e );
3048 }
3149 }
3250 }
3351
3452 return imageUrls ;
35-
3653 }
3754
3855 private String saveImage (MultipartFile image ) throws IOException {
56+ Files .createDirectories (Paths .get (IMAGE_DIR ));
3957
40- File uploadDir = new File (IMAGE_DIR );
41- if (!uploadDir .exists ()) {
42- uploadDir .mkdirs ();
58+ // 원본 파일명 가져오기 (null값 방지용)
59+ String originalFileName = image .getOriginalFilename ();
60+ if (originalFileName == null || originalFileName .isBlank ()) {
61+ originalFileName = "default.png" ;
4362 }
4463
45- String fileName = UUID .randomUUID ().toString () + "_" + image .getOriginalFilename ();
64+ // UUID + 원본 파일명으로 저장
65+ String fileName = UUID .randomUUID ().toString () + "_" + originalFileName ;
4666 File destFile = new File (IMAGE_DIR + fileName );
67+
68+ // 파일 저장
4769 image .transferTo (destFile );
4870
49- return "/images/" + fileName ; // 저장된 이미지 URL 반환
71+ return "/uploaded- images/" + fileName ; // 저장된 이미지 URL 반환
5072 }
5173
52- }
74+ }
0 commit comments