지난 글에서 올렸던 galleryService 중 업로드되는 파일의 저장경로와 파일명 지정하는 부분을 자세히 살펴보겠습니다.
먼저 application.properties에 업로드된 파일을 저장하는 경로를 지정해주었구요.
중간에 폴더 이름에 한글이 있으면 깨지는 현상이 나타나길래 전부 영어로 설정해주었습니다.

그 후, galleryService에서
@Value 어노테이션을 사용하여 part.upload.path 속성의 값을 가져와서 uploadPath 변수에 할당합니다.
업로드할 파일들을 저장할 위치를 지정하는 속성 값을 가져오는 것 입니다.

// 업로드 할 위치
@Value("${part.upload.path}")
private String uploadPath;
@Service
@Log4j2
public class GalleryService {
@Autowired
private GalleryRepository galleryRepository;
// 업로드 할 위치
@Value("${part.upload.path}")
private String uploadPath;
private String fileExtension;
private Path savePath;
// 사진첩 작성
public List<GalleryDTO> createGallery(List<MultipartFile> uploadFiles) {
// 업로드된 파일들에 대한 갤러리 DTO를 담을 리스트를 초기화합니다.
List<GalleryDTO> galleryDTOList = new ArrayList<>();
// 업로드된 각 파일에 대해 처리합니다.
for (MultipartFile uploadFile : uploadFiles) {
// 업로드된 파일이 이미지 파일인지 확인합니다.
// TODO: 확장자를 빼오는 방법으로 수정할 예정입니다.
if (!Objects.requireNonNull(uploadFile.getContentType()).startsWith("image")) {
// 업로드된 파일이 이미지 파일이 아닌 경우 로그를 출력하고 다음 파일로 넘어갑니다.
log.warn("this file is not an image type");
continue;
}
// 업로드된 파일의 원래 파일 이름을 추출합니다.
String originalName = uploadFile.getOriginalFilename();
// 파일명에서 확장자를 추출합니다.
fileExtension = StringUtils.getFilenameExtension(originalName);
// 날짜별 폴더를 생성합니다.
String folderPath = makeFolder();
// 파일에 대한 UUID를 생성합니다.
String uuid = UUID.randomUUID().toString();
// 파일을 저장할 위치와 파일 이름을 지정합니다.
String saveName = uploadPath + File.separator + folderPath + File.separator + uuid + "_" + fileName;
// 저장할 파일의 경로를 정의합니다.
savePath = Paths.get(saveName);
try {
// 업로드된 파일을 지정된 위치에 저장합니다.
uploadFile.transferTo(savePath);
// 갤러리 DTO 리스트에 해당 파일에 대한 정보를 추가합니다.
galleryDTOList.add(new GalleryDTO(fileName, uuid, folderPath));
} catch (IOException e) {
e.printStackTrace();
}
}
return galleryDTOList;
}
업로드된 파일들에 대한 갤러리 DTO를 담을 리스트를 초기화합니다.
List<GalleryDTO> galleryDTOList = new ArrayList<>();
업로드된 각 파일에 대해 처리할건데 일단 이미지 파일인지 확인해줍니다.
uploadFile.getContentType()은 업로드된 파일의 컨텐츠 타입을 가져옵니다.
null이 반환될 수 있으므로 Objects.requireNonNull()를 사용하여 null 체크를 합니다.
그 후 .startsWith("image")를 사용하여 컨텐츠 타입이 "image"로 시작하는지 확인합니다.
해당 파일이 이미지 파일이 아닌 경우 로그를 출력하고 다음 파일로 넘어가서 확인하게 됩니다.
// 업로드된 각 파일에 대해 처리합니다.
for (MultipartFile uploadFile : uploadFiles) {
// 업로드된 파일이 이미지 파일인지 확인합니다.
// TODO: 확장자를 빼오는 방법으로 수정할 예정입니다.
if (!Objects.requireNonNull(uploadFile.getContentType()).startsWith("image")) {
// 업로드된 파일이 이미지 파일이 아닌 경우 로그를 출력하고 다음 파일로 넘어갑니다.
log.warn("this file is not an image type");
continue;
}
업로드된 파일의 원래 파일의 이름을 추출하고
그 파일명에서 확장자를 추출합니다.
날짜별 폴더를 생성하기 위해 makeFolder() 메서드를 호출하고
고유성을 위해 파일에 대한 uuid를 생성해줍니다.
// 업로드된 파일의 원래 파일 이름을 추출합니다.
String originalName = uploadFile.getOriginalFilename();
// 파일명에서 확장자를 추출합니다.
fileExtension = StringUtils.getFilenameExtension(originalName);
// 날짜별 폴더를 생성합니다.
String folderPath = makeFolder();
// 파일에 대한 UUID를 생성합니다.
String uuid = UUID.randomUUID().toString();
이미지 파일이 서버에 저장될 경로와 파일명을 결정하는 부분입니다.
- uploadPath: 이미지 파일이 저장될 기본 경로입니다. 이 경로는 프로퍼티로 설정되어 있습니다.
- File.separator: 파일 경로를 구성할 때 사용되는 디렉토리 구분자입니다. Windows에서는 \\, Unix 및 Linux에서는 /입니다.
- folderPath: 이미지 파일이 저장될 폴더의 경로입니다. 보통은 날짜별로 폴더를 구분하여 이미지를 저장합니다.
- uuid: 이미지 파일명에 랜덤한 고유 식별자를 부여합니다. 이렇게 함으로써 이미지 파일명의 충돌을 방지할 수 있습니다.
- fileName: 업로드된 이미지 파일의 원래 파일명입니다.
⇒ uploadPath 폴더 안에 folderPath 폴더를 만들고,
그 안에 uuid와 fileName을 결합한 형태로 이미지 파일을 저장합니다.
String saveName = uploadPath + File.separator + folderPath + File.separator + uuid + "_" + fileName;
[ 날짜 폴더 생성 makeFolder() ]
현재 날짜를 "yyyy/MM/dd" 형식으로 포맷합니다.
String str = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
날짜를 포맷한 문자열에서 슬래시('/')를 파일 시스템의 경로 구분자(File.separator)로 대체하여 폴더 경로를 생성합니다.
String folderPath = str.replace("/", File.separator);
업로드할 파일들을 저장할 폴더의 경로를 지정합니다.
File newFile= new File(dir,"파일명");
File uploadPathFolder = new File(uploadPath, folderPath);
if(!uploadPathFolder.exists()): 폴더가 존재하지 않는 경우
- uploadPathFolder.mkdirs(): 해당 경로에 폴더를 생성합니다. 상위 디렉토리도 모두 생성됩니다.
- mkdirs 변수에는 폴더 생성 결과를 저장합니다.
생성된 폴더 경로를 반환합니다.
if(!uploadPathFolder.exists()) {
boolean mkdirs = uploadPathFolder.mkdirs();
log.info("-------------------makeFolder------------------");
log.info("uploadPathFolder.exists(): "+uploadPathFolder.exists());
log.info("mkdirs: "+mkdirs);
}
return folderPath;
💻 [ 결과 ]
설정해둔 저장경로대로 폴더가 잘 만들어지고

안에 들어가면 이렇게 해당 날짜 별로 폴더가 생성됩니다.



안에 저장된 파일명을 볼까요?
고유성 보장을 위한 uuid와 파일명이 조합된 모습을 볼 수 있습니다. 😀

'Project 댕린이집' 카테고리의 다른 글
[사진첩] 업로드 한 파일 경로 저장 (0) | 2024.06.10 |
---|---|
[사진첩] 업로드 파일(이미지) 미리보기 (0) | 2024.05.09 |
[사진첩] 파일 업로드 (0) | 2024.05.06 |
[Spring Security+JWT] HttpOnly방식을 이용한 refreshToken 발급 (0) | 2024.04.29 |
[Spring Security+JWT] JWT는 어디에 저장해야할까? localStorage vs cookie (0) | 2024.04.16 |
지난 글에서 올렸던 galleryService 중 업로드되는 파일의 저장경로와 파일명 지정하는 부분을 자세히 살펴보겠습니다.
먼저 application.properties에 업로드된 파일을 저장하는 경로를 지정해주었구요.
중간에 폴더 이름에 한글이 있으면 깨지는 현상이 나타나길래 전부 영어로 설정해주었습니다.

그 후, galleryService에서
@Value 어노테이션을 사용하여 part.upload.path 속성의 값을 가져와서 uploadPath 변수에 할당합니다.
업로드할 파일들을 저장할 위치를 지정하는 속성 값을 가져오는 것 입니다.

// 업로드 할 위치
@Value("${part.upload.path}")
private String uploadPath;
@Service
@Log4j2
public class GalleryService {
@Autowired
private GalleryRepository galleryRepository;
// 업로드 할 위치
@Value("${part.upload.path}")
private String uploadPath;
private String fileExtension;
private Path savePath;
// 사진첩 작성
public List<GalleryDTO> createGallery(List<MultipartFile> uploadFiles) {
// 업로드된 파일들에 대한 갤러리 DTO를 담을 리스트를 초기화합니다.
List<GalleryDTO> galleryDTOList = new ArrayList<>();
// 업로드된 각 파일에 대해 처리합니다.
for (MultipartFile uploadFile : uploadFiles) {
// 업로드된 파일이 이미지 파일인지 확인합니다.
// TODO: 확장자를 빼오는 방법으로 수정할 예정입니다.
if (!Objects.requireNonNull(uploadFile.getContentType()).startsWith("image")) {
// 업로드된 파일이 이미지 파일이 아닌 경우 로그를 출력하고 다음 파일로 넘어갑니다.
log.warn("this file is not an image type");
continue;
}
// 업로드된 파일의 원래 파일 이름을 추출합니다.
String originalName = uploadFile.getOriginalFilename();
// 파일명에서 확장자를 추출합니다.
fileExtension = StringUtils.getFilenameExtension(originalName);
// 날짜별 폴더를 생성합니다.
String folderPath = makeFolder();
// 파일에 대한 UUID를 생성합니다.
String uuid = UUID.randomUUID().toString();
// 파일을 저장할 위치와 파일 이름을 지정합니다.
String saveName = uploadPath + File.separator + folderPath + File.separator + uuid + "_" + fileName;
// 저장할 파일의 경로를 정의합니다.
savePath = Paths.get(saveName);
try {
// 업로드된 파일을 지정된 위치에 저장합니다.
uploadFile.transferTo(savePath);
// 갤러리 DTO 리스트에 해당 파일에 대한 정보를 추가합니다.
galleryDTOList.add(new GalleryDTO(fileName, uuid, folderPath));
} catch (IOException e) {
e.printStackTrace();
}
}
return galleryDTOList;
}
업로드된 파일들에 대한 갤러리 DTO를 담을 리스트를 초기화합니다.
List<GalleryDTO> galleryDTOList = new ArrayList<>();
업로드된 각 파일에 대해 처리할건데 일단 이미지 파일인지 확인해줍니다.
uploadFile.getContentType()은 업로드된 파일의 컨텐츠 타입을 가져옵니다.
null이 반환될 수 있으므로 Objects.requireNonNull()를 사용하여 null 체크를 합니다.
그 후 .startsWith("image")를 사용하여 컨텐츠 타입이 "image"로 시작하는지 확인합니다.
해당 파일이 이미지 파일이 아닌 경우 로그를 출력하고 다음 파일로 넘어가서 확인하게 됩니다.
// 업로드된 각 파일에 대해 처리합니다.
for (MultipartFile uploadFile : uploadFiles) {
// 업로드된 파일이 이미지 파일인지 확인합니다.
// TODO: 확장자를 빼오는 방법으로 수정할 예정입니다.
if (!Objects.requireNonNull(uploadFile.getContentType()).startsWith("image")) {
// 업로드된 파일이 이미지 파일이 아닌 경우 로그를 출력하고 다음 파일로 넘어갑니다.
log.warn("this file is not an image type");
continue;
}
업로드된 파일의 원래 파일의 이름을 추출하고
그 파일명에서 확장자를 추출합니다.
날짜별 폴더를 생성하기 위해 makeFolder() 메서드를 호출하고
고유성을 위해 파일에 대한 uuid를 생성해줍니다.
// 업로드된 파일의 원래 파일 이름을 추출합니다.
String originalName = uploadFile.getOriginalFilename();
// 파일명에서 확장자를 추출합니다.
fileExtension = StringUtils.getFilenameExtension(originalName);
// 날짜별 폴더를 생성합니다.
String folderPath = makeFolder();
// 파일에 대한 UUID를 생성합니다.
String uuid = UUID.randomUUID().toString();
이미지 파일이 서버에 저장될 경로와 파일명을 결정하는 부분입니다.
- uploadPath: 이미지 파일이 저장될 기본 경로입니다. 이 경로는 프로퍼티로 설정되어 있습니다.
- File.separator: 파일 경로를 구성할 때 사용되는 디렉토리 구분자입니다. Windows에서는 \\, Unix 및 Linux에서는 /입니다.
- folderPath: 이미지 파일이 저장될 폴더의 경로입니다. 보통은 날짜별로 폴더를 구분하여 이미지를 저장합니다.
- uuid: 이미지 파일명에 랜덤한 고유 식별자를 부여합니다. 이렇게 함으로써 이미지 파일명의 충돌을 방지할 수 있습니다.
- fileName: 업로드된 이미지 파일의 원래 파일명입니다.
⇒ uploadPath 폴더 안에 folderPath 폴더를 만들고,
그 안에 uuid와 fileName을 결합한 형태로 이미지 파일을 저장합니다.
String saveName = uploadPath + File.separator + folderPath + File.separator + uuid + "_" + fileName;
[ 날짜 폴더 생성 makeFolder() ]
현재 날짜를 "yyyy/MM/dd" 형식으로 포맷합니다.
String str = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
날짜를 포맷한 문자열에서 슬래시('/')를 파일 시스템의 경로 구분자(File.separator)로 대체하여 폴더 경로를 생성합니다.
String folderPath = str.replace("/", File.separator);
업로드할 파일들을 저장할 폴더의 경로를 지정합니다.
File newFile= new File(dir,"파일명");
File uploadPathFolder = new File(uploadPath, folderPath);
if(!uploadPathFolder.exists()): 폴더가 존재하지 않는 경우
- uploadPathFolder.mkdirs(): 해당 경로에 폴더를 생성합니다. 상위 디렉토리도 모두 생성됩니다.
- mkdirs 변수에는 폴더 생성 결과를 저장합니다.
생성된 폴더 경로를 반환합니다.
if(!uploadPathFolder.exists()) {
boolean mkdirs = uploadPathFolder.mkdirs();
log.info("-------------------makeFolder------------------");
log.info("uploadPathFolder.exists(): "+uploadPathFolder.exists());
log.info("mkdirs: "+mkdirs);
}
return folderPath;
💻 [ 결과 ]
설정해둔 저장경로대로 폴더가 잘 만들어지고

안에 들어가면 이렇게 해당 날짜 별로 폴더가 생성됩니다.



안에 저장된 파일명을 볼까요?
고유성 보장을 위한 uuid와 파일명이 조합된 모습을 볼 수 있습니다. 😀

'Project 댕린이집' 카테고리의 다른 글
[사진첩] 업로드 한 파일 경로 저장 (0) | 2024.06.10 |
---|---|
[사진첩] 업로드 파일(이미지) 미리보기 (0) | 2024.05.09 |
[사진첩] 파일 업로드 (0) | 2024.05.06 |
[Spring Security+JWT] HttpOnly방식을 이용한 refreshToken 발급 (0) | 2024.04.29 |
[Spring Security+JWT] JWT는 어디에 저장해야할까? localStorage vs cookie (0) | 2024.04.16 |