1515import software .amazon .awssdk .services .s3 .presigner .model .GetObjectPresignRequest ;
1616
1717import java .io .File ;
18+ import java .net .URI ;
1819import java .nio .file .Files ;
1920import java .nio .file .Path ;
2021import java .time .Duration ;
@@ -78,7 +79,7 @@ public File downloadFile(String fileUrl) {
7879
7980 try {
8081 // URL에서 순수 Key만 추출
81- String pureKey = fileUrl . contains ( ".com/" ) ? fileUrl . split ( ".com/" )[ 1 ] : fileUrl ;
82+ String pureKey = extractKey ( fileUrl ) ;
8283
8384 // 다운로드 받을 로컬 임시 파일 경로 생성
8485 File tempFile = File .createTempFile ("s3_download_" , ".mp3" );
@@ -112,7 +113,7 @@ public String getPresignedUrl(String key, Duration durationUrl) {
112113 if (key == null || key .isEmpty ()) return null ;
113114
114115 // URL에서 도메인을 제외한 순수 'Key'만 추출 (만약 전체 URL이 들어올 경우를 대비)
115- String pureKey = key . contains ( ".com/" ) ? key . split ( ".com/" )[ 1 ] : key ;
116+ String pureKey = extractKey ( key ) ;
116117
117118 GetObjectPresignRequest presignRequest = GetObjectPresignRequest .builder ()
118119 .signatureDuration (durationUrl )
@@ -122,6 +123,18 @@ public String getPresignedUrl(String key, Duration durationUrl) {
122123 return s3Presigner .presignGetObject (presignRequest ).url ().toString ();
123124 }
124125
126+ /**
127+ * DB/외부 입력에는 순수 key가 오는 게 기본이지만, 레거시 데이터나 실수로 전체 URL이
128+ * 들어오는 경우를 대비해 호스트가 아닌 경로 기준으로 key를 추출한다(스토리지 제공자 무관).
129+ */
130+ private String extractKey (String input ) {
131+ if (!input .startsWith ("http://" ) && !input .startsWith ("https://" )) {
132+ return input ;
133+ }
134+ String path = URI .create (input ).getPath ();
135+ return path .startsWith ("/" ) ? path .substring (1 ) : path ;
136+ }
137+
125138 private String determineContentType (String key ) {
126139 if (key .endsWith (".mp3" )) return "audio/mpeg" ;
127140 if (key .endsWith (".png" )) return "image/png" ;
@@ -149,7 +162,7 @@ public void deleteFile(String fileUrl) {
149162
150163 try {
151164 // 1. 전체 URL에서 순수 Key 추출 (기존 getPresignedUrl에 있던 방식과 동일하게 처리)
152- String pureKey = fileUrl . contains ( ".com/" ) ? fileUrl . split ( ".com/" )[ 1 ] : fileUrl ;
165+ String pureKey = extractKey ( fileUrl ) ;
153166
154167 // 2. AWS SDK v2 전용 삭제 요청 객체 생성
155168 DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest .builder ()
0 commit comments