From 379fef86e051d68da9953f4fe76abc406b268b6a Mon Sep 17 00:00:00 2001 From: yoon Date: Tue, 21 Jan 2025 20:45:18 +0900 Subject: [PATCH] =?UTF-8?q?=ED=94=84=EB=A1=9C=ED=95=84=20=ED=8C=8C?= =?UTF-8?q?=EC=9D=BC=20=EC=97=85=EB=A1=9C=EB=93=9C=20=EC=84=9C=EB=B9=84?= =?UTF-8?q?=EC=8A=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../localhost/service/FileService.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/main/java/io/company/localhost/service/FileService.java diff --git a/src/main/java/io/company/localhost/service/FileService.java b/src/main/java/io/company/localhost/service/FileService.java new file mode 100644 index 0000000..abb6708 --- /dev/null +++ b/src/main/java/io/company/localhost/service/FileService.java @@ -0,0 +1,69 @@ +/************************************************************ + * + * @packageName : io.company.localhost.FileService + * @fileName : FileService.java + * @author : 박지윤 + * @date : 25.01.17 + * @description : + * + * =========================================================== + * DATE AUTHOR NOTE + * ----------------------------------------------------------- + * 24.01.17 박지윤 최초 생성 + * + *************************************************************/ +package io.company.localhost.service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.UUID; +import org.apache.commons.io.FilenameUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; +import lombok.RequiredArgsConstructor; + +@Service +@RequiredArgsConstructor +public class FileService { + + + @Value("${filePath.profile}") + private String uploadPath; + + /** + * 파일 업로드 + * + * @param file + * @param directory + * @return + * @throws RuntimeException + */ + public String uploadFile(MultipartFile file, String directory) { + try { + // 원본 파일명 + String originalFilename = file.getOriginalFilename(); + // 파일 확장자 + String extension = FilenameUtils.getExtension(originalFilename); + // UUID를 사용하여 고유한 파일명 생성 + String newFilename = UUID.randomUUID().toString() + "." + extension; + + // 최종 저장 경로 생성 (기본경로 + 하위디렉토리 + 파일명) + Path targetPath = Paths.get(uploadPath, directory, newFilename); + // 저장될 디렉토리가 없는 경우 생성 + Files.createDirectories(targetPath.getParent()); + + // 동일 파일명이 있을 경우 덮어쓰기 + Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING); + + // 저장된 파일의 상대 경로 반환 + return directory + "/" + newFilename; + + } catch (IOException e) { + throw new RuntimeException("파일 업로드 실패: " + e.getMessage()); + } + } +} \ No newline at end of file