FTP서버에 파일 저장
1.구조
실제 파일은 ftp 에 저장하고
저장된 주소는 IIS에서 생성한 웹서버 주소를 붙여서 저장한다
IIS에서 생성한 ftp서버와 웹서버가 같은 폴더로 연결되어있어서
url에 http로 쳐서 들어가면 파일에 접근이 가능하다
Controller 단
@RequestMapping("/api/saveFile.do")
public String ajaxDiagnosisInflFileSave(@RequestParam("uploadFile") MultipartFile uploadFile, @RequestParam("idx") String idx, Model model) throws Exception {
String newFilename;
String originalFilename = uploadFile.getOriginalFilename();
if (originalFilename != null && originalFilename.contains(".")) {
// Find the last index of the period to get the extension
int dotIndex = originalFilename.lastIndexOf(".");
String extension = originalFilename.substring(dotIndex);
newFilename = idx + extension;
Service.saveFile(uploadFile,idx,newFilename);
}
return "jsonView";
}
서비스단
단순 저장(덮어씌우기방식)
@Service("egovService")
public class EgovServiceImpl extends EgovAbstractServiceImpl implements EgovService {
@Resource(name = "DAO")
private DAO DAO;
private static final String FTP_SERVER_USER = EgovProperties.getProperty("Globals.ftpServerUser");
private static final String FTP_SERVER_PASSWORD = EgovProperties.getProperty("Globals.ftpServerPassword");
private static final String FTP_SERVER_IP = EgovProperties.getProperty("Globals.ftpServerIp");// FTP 서버 IP 주소(ex:localhost)
private static final int FTP_SERVER_PORT = Integer.parseInt(EgovProperties.getProperty("Globals.ftpServerPort")); // FTP 서버 포트(ex:21)
private static final String FTP_SERVER_WEB_PORT = EgovProperties.getProperty("Globals.ftpServerWebPort"); //FTP 웹 파일 포트(ex:8088)
private static final String TARGET_DIR = "/PDF"; // 원격 서버의 대상 디렉토리
private static final String ROOT_DIR = ""; // 루트 디렉토리 (필요 시 설정)
@Override
public void saveFile(final MultipartFile file, final String idx, final String filename) throws Exception {
FTPClient client = new FTPClient();
try (InputStream input = file.getInputStream()) {
String remoteFilePath = TARGET_DIR + "/" + filename;
client.connect(FTP_SERVER_IP, FTP_SERVER_PORT);
// FTP Server 로그인 수행
if (client.login(FTP_SERVER_USER, FTP_SERVER_PASSWORD)) {
client.setBufferSize(1000);
client.enterLocalPassiveMode();
client.setFileType(FTP.BINARY_FILE_TYPE);
// 필요한 경우 루트 디렉토리 생성
if (!ROOT_DIR.isEmpty()) {
client.mkd("/" + ROOT_DIR);
}
// FTP Server에 파일 저장(전송)
if (!client.storeFile(remoteFilePath, input)) {
throw new Exception("File store failed");
}
// DB 업데이트
String fullUrl = "http://" + FTP_SERVER_IP + ":" + FTP_SERVER_WEB_PORT + remoteFilePath;
FileApiRequest fileApiRequest = new FileApiRequest();
fileApiRequest.setFileUrl(fullUrl);
fileApiRequest.setFlagCd(idx);
DAO.updateFile(fileApiRequest);
// FTP 서버 접속 해제
client.logout();
client.disconnect();
} else {
throw new Exception("Login Failed");
}
} catch (Exception e) {
client.logout();
client.disconnect();
System.out.println("done");
throw e;
}
}
public FileApiResponse selectFileUrl(String vo) throws Exception{
FileApiRequest fileApiRequest = new FileApiRequest();
fileApiRequest.setFlagCd(vo);
return DAO.selectFileUrl(fileApiRequest);
}
}
동일한 파일명으로 덮어씌우면
파일이 캐쉬에 남기때문에 파일이 변경되어도 화면상 바로 변경된 파일을 로드 못하는 문제가 있었다.
그래서 저장방식을 바꿔보았다.
날짜명의 폴더를 생성하고
파일명을 저장하는 시간의 초단위까지 집어넣어 중복되지않도록 저장했다
그렇게하니 바로바로 안보이는 문제가 해결됐다.
@Override
public void saveFile(final MultipartFile file, final String idx, final String filename) throws Exception {
FTPClient client = new FTPClient();
try (InputStream input = file.getInputStream()) {
// 현재 날짜 가져오기
LocalDate today = LocalDate.now();
String todayDir = today.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
// 현재 시간으로 타임스탬프 생성
LocalDateTime now = LocalDateTime.now();
String timestamp = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
// 확장자 분리
int dotIndex = filename.lastIndexOf('.');
String name = (dotIndex == -1) ? filename : filename.substring(0, dotIndex);
String extension = (dotIndex == -1) ? "" : filename.substring(dotIndex);
// 유니크한 파일명 생성
String uniqueFilename = name + "_" + timestamp + extension;
String remoteFilePath = TARGET_DIR + "/" + todayDir + "/" + uniqueFilename;
client.connect(FTP_SERVER_IP, FTP_SERVER_PORT);
// FTP Server 로그인 수행
if (client.login(FTP_SERVER_USER, FTP_SERVER_PASSWORD)) {
client.setBufferSize(1000);
client.enterLocalPassiveMode();
client.setFileType(FTP.BINARY_FILE_TYPE);
// 필요한 경우 루트 디렉토리 생성
if (!ROOT_DIR.isEmpty()) {
client.mkd("/" + ROOT_DIR);
}
// 오늘 날짜 폴더 생성
client.mkd("/" + ROOT_DIR + "/" + TARGET_DIR + "/" + todayDir);
// FTP Server에 파일 저장(전송)
if (!client.storeFile(remoteFilePath, input)) {
throw new Exception("File store failed");
}
// DB 업데이트
String fullUrl = "http://" + FTP_SERVER_IP + ":" + FTP_SERVER_WEB_PORT + remoteFilePath;
FileApiRequest fileApiRequest = new FileApiRequest();
fileApiRequest.setFileUrl(fullUrl);
fileApiRequest.setFlagCd(idx);
DAO.updateFile(fileApiRequest);
// FTP 서버 접속 해제
client.logout();
client.disconnect();
} else {
throw new Exception("Login Failed");
}
} catch (Exception e) {
client.logout();
client.disconnect();
System.out.println("done");
throw e;
}
}
반응형
'서버&백엔드 > 🔥 JAVA' 카테고리의 다른 글
Java | 스트림(Stream) 완전 정복 - 숫자형 (0) | 2024.11.01 |
---|---|
톰캣 자바 메모리풀 사이즈 설정 (0) | 2024.08.07 |
이클립스, 톰캣 | 파일업로드시 프로젝트 새로고침해야지 뜰때 (0) | 2024.03.12 |
변수명이 js단에서 소문자로 변경돼서 넘어오는 경우 (0) | 2024.02.13 |
Builder패턴 (0) | 2023.04.18 |