프로필 파일 업로드 서비스

This commit is contained in:
yoon 2025-01-21 20:45:18 +09:00
parent 1973322cbf
commit 379fef86e0

View File

@ -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());
}
}
}