public String storeFile(MultipartFile file) throws IOException {
-> 이 부분은 메서드의 선언임. storeFile 메서드는 MultipartFile 타입의 file을 매개변수로 받아들이며,
IOException을 던질 수 있음. MultipartFile은 Spring에서 파일 업로드를 처리할 때 사용하는 인터페이스이며,
IOException은 파일 입출력(I/O) 연산 도중 발생할 수 있는 예외를 처리하는 클래스임.
GridFSFile gridFsFile = gridFsTemplate.store(file.getInputStream(),
file.getOriginalFilename(), file.getContentType());
-> gridFsTemplate.store() 메서드를 사용하여 파일을 MongoDB의 GridFS에 저장함.
store() 메서드는 파일의 내용을 나타내는 InputStream, 파일의 원래 이름, 파일의 컨텐츠 타입을 인자로 받음.
이 메서드는 저장한 파일의 정보를 GridFSFile 객체로 반환.
try {
Path copyLocation = Paths.get("C:\\file" + File.separator +
StringUtils.cleanPath(file.getOriginalFilename()));
-> 이 부분에서는 파일을 저장할 위치를 지정.
Paths.get() 메서드를 사용하여 Path 객체를 생성.
Path 객체는 파일 또는 디렉토리의 경로를 표현.
StringUtils.cleanPath() 메서드는 파일 이름에서 부적절한 문자를 제거.
이렇게 하면 실제 파일 시스템에 피해를 줄 수 있는 문자 또는 경로를 방지할 수 있음.
Files.copy(file.getInputStream(), copyLocation, StandardCopyOption.REPLACE_EXISTING);
-> Files.copy() 메서드를 사용하여 파일을 복사.
이 메서드는 파일의 내용을 나타내는 InputStream, 복사할 위치를 나타내는 Path 객체, 복사 옵션을 인자로 받음.
StandardCopyOption.REPLACE_EXISTING 옵션은 같은 이름의 파일이 존재하는 경우 해당 파일을 덮어쓰라는 의미.
} catch (Exception e) {
e.printStackTrace();
throw new IOException("Could not store file " +
file.getOriginalFilename() +
". Please try again!", e);
}
-> 이 부분은 예외 처리 부분.
파일 복사 도중 예외가 발생하면 해당 예외를 콘솔에 출력하고, 새로운 IOException을 던짐.
이때 IOException의 메시지는 "Could not store file [파일 이름]. Please try again!"임.
실행이 안될 경우 IOException을 호출하는 부분에서 system.out.println(e.getMessage);로 확인가능
return gridFsFile.getId().toString();
}
-> storeFile 메서드는 MongoDB에 저장한 파일의 ID를 문자열로 변환하여 반환.
이 ID는 나중에 파일을 검색하거나 다운로드하는 데 사용됨.
아래 전체코드
// DAO임
public String storeFile(MultipartFile file) throws IOException {
GridFSFile gridFsFile = gridFsTemplate.store(file.getInputStream(), file.getOriginalFilename(), file.getContentType());
// 디렉토리에 파일 저장
try {
// 파일 저장 경로 설정
Path diretoryPath =
Paths.get("C:\\file" + File.separator + StringUtils.cleanPath(file.getOriginalFilename()));
// StandardCopyOption은 Java NIO의 파일 복사 동작을 정의하는 열거형(enum),
// REPLACE_EXISTING: 이 옵션은 대상 위치에 이미 파일이 존재하는 경우, 해당 파일을 덮어쓰는 것을 허용함.
Files.copy(file.getInputStream(), diretoryPath, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
e.printStackTrace();
throw new IOException(file.getOriginalFilename() + " 다시 시도해주세요.", e);
}
return gridFsFile.getId().toString();
}