|
| 1 | +package com.zzang.chongdae.storage.service; |
| 2 | + |
| 3 | +import com.zzang.chongdae.global.exception.MarketException; |
| 4 | +import com.zzang.chongdae.storage.exception.StorageErrorCode; |
| 5 | +import java.io.IOException; |
| 6 | +import java.nio.file.Files; |
| 7 | +import java.nio.file.Path; |
| 8 | +import java.nio.file.Paths; |
| 9 | +import java.nio.file.StandardCopyOption; |
| 10 | +import java.util.Set; |
| 11 | +import java.util.UUID; |
| 12 | +import lombok.RequiredArgsConstructor; |
| 13 | +import org.springframework.beans.factory.annotation.Value; |
| 14 | +import org.springframework.web.multipart.MultipartFile; |
| 15 | +import org.springframework.web.util.UriComponentsBuilder; |
| 16 | + |
| 17 | +@RequiredArgsConstructor |
| 18 | +public class LocalStorageService implements StorageService { |
| 19 | + |
| 20 | + private static final Set<String> ALLOW_IMAGE_EXTENSIONS = Set.of("jpg", "jpeg", "png", "gif", "bmp", "svg"); |
| 21 | + |
| 22 | + @Value("${storage.redirectUrl}") |
| 23 | + private String redirectUrl; |
| 24 | + |
| 25 | + @Value("${storage.path}") |
| 26 | + private String storagePath; |
| 27 | + |
| 28 | + @Override |
| 29 | + public String uploadFile(MultipartFile file) { |
| 30 | + try { |
| 31 | + String extension = getFileExtension(file); |
| 32 | + validateFileExtension(extension); |
| 33 | + String newFilename = UUID.randomUUID() + "." + extension; |
| 34 | + Path uploadPath = Paths.get(storagePath); |
| 35 | + Path filePath = uploadPath.resolve(newFilename); |
| 36 | + Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING); |
| 37 | + return createUri(filePath.toString()); |
| 38 | + } catch (IOException e) { |
| 39 | + throw new RuntimeException(e); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | + private String getFileExtension(MultipartFile file) { |
| 45 | + String originalFilename = file.getOriginalFilename(); |
| 46 | + if (originalFilename == null || !originalFilename.contains(".")) { |
| 47 | + throw new MarketException(StorageErrorCode.INVALID_FILE); |
| 48 | + } |
| 49 | + return originalFilename.substring(originalFilename.lastIndexOf('.') + 1).toLowerCase(); |
| 50 | + } |
| 51 | + |
| 52 | + private void validateFileExtension(String extension) { |
| 53 | + if (!ALLOW_IMAGE_EXTENSIONS.contains(extension)) { |
| 54 | + throw new MarketException(StorageErrorCode.INVALID_FILE_EXTENSION); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + private String createUri(String objectKey) { |
| 59 | + return UriComponentsBuilder.newInstance() |
| 60 | + .scheme("https") |
| 61 | + .host(redirectUrl) |
| 62 | + .path("/" + objectKey) |
| 63 | + .build(false) |
| 64 | + .toString(); |
| 65 | + } |
| 66 | +} |
0 commit comments