|
1 | 1 | package com.back.web7_9_codecrete_be.global.storage; |
2 | 2 |
|
| 3 | +import lombok.RequiredArgsConstructor; |
| 4 | +import org.springframework.beans.factory.annotation.Value; |
3 | 5 | import org.springframework.stereotype.Service; |
4 | 6 | import org.springframework.web.multipart.MultipartFile; |
| 7 | +import software.amazon.awssdk.core.sync.RequestBody; |
| 8 | +import software.amazon.awssdk.services.s3.S3Client; |
| 9 | +import software.amazon.awssdk.services.s3.model.PutObjectRequest; |
5 | 10 |
|
| 11 | +import java.io.IOException; |
6 | 12 | import java.util.UUID; |
7 | 13 |
|
8 | 14 | @Service |
| 15 | +@RequiredArgsConstructor |
9 | 16 | public class S3FileStorageService implements FileStorageService { |
| 17 | + |
| 18 | + private final S3Client s3Client; |
| 19 | + |
| 20 | + @Value("${cloud.aws.s3.bucket}") |
| 21 | + private String bucket; |
| 22 | + |
| 23 | + @Value("${cloud.aws.region.static}") |
| 24 | + private String region; |
| 25 | + |
| 26 | + // 공용 업로드 메서드 |
| 27 | + @Override |
| 28 | + public String upload(MultipartFile file, String basePath) { |
| 29 | + |
| 30 | + String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename(); |
| 31 | + String key = basePath + "/" + fileName; |
| 32 | + |
| 33 | + try { |
| 34 | + PutObjectRequest putObjectRequest = PutObjectRequest.builder() |
| 35 | + .bucket(bucket) |
| 36 | + .key(key) |
| 37 | + .contentType(file.getContentType()) |
| 38 | + .build(); |
| 39 | + |
| 40 | + s3Client.putObject( |
| 41 | + putObjectRequest, |
| 42 | + RequestBody.fromInputStream(file.getInputStream(), file.getSize()) |
| 43 | + ); |
| 44 | + |
| 45 | + } catch (IOException e) { |
| 46 | + throw new RuntimeException("S3 파일 업로드 실패", e); |
| 47 | + } |
| 48 | + |
| 49 | + return "https://" + bucket + ".s3." + region + ".amazonaws.com/" + key; |
| 50 | + } |
| 51 | + |
10 | 52 | @Override |
11 | | - public String upload(MultipartFile file) { |
| 53 | + public void delete(String fileUrl) { |
| 54 | + |
| 55 | + if (fileUrl == null || fileUrl.isBlank()) { |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + String prefix = "https://" + bucket + ".s3." + region + ".amazonaws.com/"; |
| 60 | + if (!fileUrl.startsWith(prefix)) { |
| 61 | + throw new IllegalArgumentException("잘못된 S3 파일 URL입니다."); |
| 62 | + } |
12 | 63 |
|
13 | | - // 임시 URL 생성 |
14 | | - String fakeFileName = UUID.randomUUID() + "_" + file.getOriginalFilename(); |
| 64 | + String key = fileUrl.substring(prefix.length()); |
15 | 65 |
|
16 | | - return "https://dummy-cdn.codecrete.com/profile/" + fakeFileName; |
| 66 | + s3Client.deleteObject(builder -> builder |
| 67 | + .bucket(bucket) |
| 68 | + .key(key) |
| 69 | + ); |
17 | 70 | } |
18 | 71 | } |
0 commit comments