💬
목차
< 뒤로가기
인쇄

캐모마일 파일 모듈 가이드

개요

chamomile-file 모듈은 파일 관리, 파일 업로드, 파일 다운로드, 파일 정보 로깅 4가지 기능을 담당한다.

사용법

dependency

<dependency>
  <groupId>net.lotte.chamomile.module</groupId>
  <artifactId>chamomile-file</artifactId>
  <version>3.0.0-SNAPSHOT</version>
</dependency>

파일 관리

개요

FileUtil은 시스템 내의 용량 체크, 파일 핸들링, 권한 제어 등의기능을 담당한다.

권한 제어는 리눅스 환경에서 Owner의 권한만 제어가 가능하다.

FileUtil api목록

메서드명 파라미터 반환값 설명
getStorageInfo String path long 해당 디스크의 가용 용량을 반환.(MB단위)
getStorageInfo String path, FileSizeUnit unit long 해당 디스크의 가용용량을 반환(byte단위)
makeFile String path, String filename, byte[] data 파일을 지정한 경로에 생성
removeFile String path boolean 파일을 삭제
copyFileToDir String src, String destPath 파일을 디렉토리로 복사
copyDir String src, String desc 디렉토리 복사
makeDir String path boolean 디렉토리 생성
removeDirForce String path 디렉토리 강제삭제. 디렉토리가 비어있지 않아도 모든 디렉토리 삭제
removeDir String path 디렉토리 삭제. 디렉토리가 비어있지 않으면 Exception
moveFile String src, String desc 파일이동
moveDir String src, String desc 디렉토리 이동
changeFileAuthReadable File file, boolean readable 파일의 읽기권한 제어
changeFileAuthWriteable File file, boolean writable 파일의 쓰기권한 제어
changeFileAuthExecutable File file, boolean executable 파일의 실행권한 제어

예제

[가용용량 체크]
localPath: 원하는 경로의 String을 입력

assertTrue(FileUtil.getStorageInfo(localPath) > 0);

[파일생성 및 삭제]
임시파일을과 임시디렉토리를 생성한다.

File file = new File(localfilePath);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
    bw.write("This is test");
}

생성한 임시파일의 byte데이터를 makeFile API에 넘긴다.

byte[] byt = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
FileUtil.makeFile(dirPath, "테스트.txt", byt);

[디렉토리 생성 및 삭제]

현재 path에 dirTest라는 디렉토리를 만들고 삭제한다.

assertTrue(FileUtil.makeDir("./dirTest"));
try {
    FileUtil.removeDirForce("./dirTest");
} catch (IOException e) {
    fail(e.getMessage());
}

[파일 및 디렉토리 복사]
첫번째 임시 디렉토리와 임시 파일을 생성한다.

FileUtil.copyFileToDir(localfilePath, localDirPath);
/* 첫번째 임시디렉토리를 두번쨰 임시디렉토리로 복사 */
FileUtil.copyDir(localDirPath, "./test2");
FileUtil.removeDirForce("./test2");
FileUtil.removeDirForce(localDirPath); 

[파일 및 디렉토리 이동]

String moveDirPath = localPath + "이동디렉토리";
FileUtil.moveFile(localfilePath, moveDirPath);
assertTrue(new File(moveDirPath).listFiles().length > 0);
FileUtil.removeDirForce(moveDirPath);

파일 업로드

개요

FileUploader는 웹 서비스 요청으로 파일 업로드를 수행한다.

업로드 가능한 확장자, 파일 용량 체크, 파일 이름 난독화 등의 기능을 수행한다.

설정

properties 통한 설정(application.properties)

##FILE
chmm.file.repositoryPath=/files // 파일 저장소 위치
chmm.file.upload.allowExtension="" // 허용할 확장자 이름 ',' 로 구분한다.
chmm.file.upload.maxSize=20MB // 최대 업로드 용량 KB,MB,GB를 붙여야 한다.
chmm.file.upload.dirctoryDateNameFormat=yyyy/MM //디렉토리를 날짜별로 생성해줄때의 포맷 이름

사용방법

요청으로 들어온 file은 FileUploader에 넘겨준다.
업로드 수행된 후 관련 정보가 반환되며 DB에 추가로 저장하는 작업을 한다면 FileMetadataInfoEntity[] fileVo 를 이용하면 된다.

@Autowird 
FileUploader fileUploader;

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void fileUpload(MultipartFile file) throws Exception {
    FileMetadataInfoEntity[] fileVo = fileUploader.fileUpload(
        new MultipartFile[] {file});
}

FileMetadataInfoEntity 객체 제공 데이터

메서드명 데이터 타입 설명
fileMetaDataCode String 업로드 후 hash값으로 변환된 파일명.
fileUploadPath String 업로드된 실제 경로
originalFileName String 실제 파일 이름
fileSize long 업로드된 파일의 크기

파일 다운로드

개요

FileDownloader는 웹 서비스상에서 파일을 클라이언트에게 전송하는 역할을 한다.

사용법

1) 루트 디렉토리에서 파일 다운로드 하는 경우

@Autowird 
FileDownloader fileDownloader;

@GetMapping("/download/{fileName}")
protected ResponseEntity<byte[]> download(@PathVariable String fileName){
    return FileDownloader.fileDownload(
        fileName,  // 서버에 실제 파일주소
        "text.txt"); //클라이언트에 노출할 파일명

2) 개인정보가 포함된 파일 다운로드의 경우

@Autowird 
FileDownloader fileDownloader;

@GetMapping("/download/{fileName}")
protected ResponseEntity<byte[]> download(@PathVariable String fileName,String message){
    return FileDownloader.fileDownload(
        fileName,  // 서버에 실제 파일주소
        "text.txt", //클라이언트에 노출할 파일명
        ,message); // 개인정보 파일은 다운로드 하는 사유

파일 로깅

개요

파일 업로드/다운로드/삭제 이력은 chamomile-logging 모듈을 의존하여 구현하였으며,
FileDownloader,FileUploader,FileUtil 사용시 아래와 같은 로그가 파일 및 데이터베이스에 다음과 같이 저장한다.

파일 다운로드시 남기는 로그 내용
로그 날짜, 리퀘스트 아이디, 세션 아이디, 사용자 아이디, 접속 IP, 접속 URL, 다운로드 파일명, 파일 사이즈, 다운로드 사유

파일 업로드/삭제시 남기는 로그 내용
로그 날짜, 리퀘스트 아이디, 세션 아이디, 사용자 아이디, 접속 IP, 접속 URL,업로드 경로,업로드 파일명,파일 사이즈, 파일 업로드/삭제 상태

CREATE TABLE CHMM_FILE_DOWNLOAD_LOGGING  (
    file_downlaod_logging_id BIGINT PRIMARY KEY, // ID
    client_id VARCHAR(30),              // 사용자 ID
    client_ip VARCHAR(50),              // 사용자 IP
    request_url VARCHAR(255),           // 요청 URL
    request_id VARCHAR(20),             // 요청 ID
    session_id VARCHAR(20),             // 세션 ID
    is_privacy_file char(1),            // 개인정보 파일 여부
    privacy_file_download_reason  VARCHAR(255), // 개인정보 파일 다운로드 사유
    file_hash VARCHAR(255),             // 파일 해시
    original_file_name VARCHAR(255),    // 원본 파일 이름
    file_path  VARCHAR(255),            // 파일 실제 위치
    file_size INT,                      // 파일 사이즈
    log_date TIMESTAMP                  // 로그 날짜
);

CREATE TABLE CHMM_FILE_LOGGING  (
    file_logging_id BIGINT PRIMARY KEY,
    client_id VARCHAR(30),              // 사용자 ID
    client_ip VARCHAR(50),              // 사용자 IP
    request_url VARCHAR(255),           // 요청 URL
    request_id VARCHAR(20),             // 요청 ID
    session_id VARCHAR(20),             // 세션 ID
    file_action_type VARCHAR(10),       // 파일 관리 상태
    original_file_name VARCHAR(255),   // 원래 파일 이름
    file_size INT,                      // 파일 크기
    file_path VARCHAR(255),             // 실제 파일 위치
    file_hash VARCHAR(20),              // 파일 해시 코드
    log_date TIMESTAMP                  // 로깅 날짜
);
이전 FTP
다음 메뉴