일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 자바스크립트 인라인
- BindingResult
- cmd
- 타임리프와 스프링
- js
- 명령어
- linux
- 스프링부트
- 룸북
- select
- 프로젝트 클린
- 비밀번호 변경 명령어
- StringUtils.hasText
- 리눅스
- Java
- it
- 설정
- Intellij
- 시퀀스 조회
- Test 룸북 사용하기
- 추천 프로그램
- JSON
- 순서 보장
- 함수 인자값 id
- 하모니카 OS 5
- 다른사람 프로젝트 수정전 가져야할 자세
- 개발시작전 자세
- 타임리프
- 추천 사이트
- #{..}
Archives
- Today
- Total
웹개발 블로그
[JAVA]FTP 서버 업로드 본문
⬇️ FTP 서버 연결 설정 및 연동 , 업로드만 구현했음
package egovframework.onpia.crm.sms.util;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.SocketException;
public class FTPControl { // FTP 연결, 파일 업로드 등을 수행하는 메서드
private static final Logger logger = LoggerFactory.getLogger(FTPControl.class);
/**FTP 서버로 파일을 업로드
* @Param : 서버 정보(server,port), 인증 정보(username, password), 로컬파일 경로, 원격파일 경로*/
public static void uploadFile(String server, int port, String username, String password, String localFilePath, String remoteFilePath) throws Exception {
FTPClient ftpClient = new FTPClient(); // FTP 연결과 파일 전송에 사용된다.
//localFilePath : 전송하려는 파일이 저장된 로컬 시스템(클라이언트)에서의 파일 경로 의미
//remoteFilePath : 파일을 전송하고자 하는 원격시스템(FTP)에서의 파일 경로를 의미 ( 전송하려는 파일이 FTP 서버에서 어느 위치에 저장될지를 지정)
FileInputStream fileInputStream = null;
try {
ftpClient.setControlEncoding("UTF-8");
ftpClient.connect(server, port);//서버정보
int resultCode = ftpClient.getReplyCode();//접속확인
if (!FTPReply.isPositiveCompletion(resultCode)) {// 응답 false이면 연결해제
logger.error("[FTP] Server refused connection.");
ftpClient.disconnect();//연결해제
return;
}else{
if(!(ftpClient.login(username, password))){//로그인
logger.error("[FTP] Login error");
return;
}
logger.info("[FTP] Success connection.");
logger.info("[FTP] Login successful.");
}
ftpClient.setSoTimeout(1000); //Timeout 설정 (기본이 1분 = 60000)
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//이진 파일 타입 설정(이미지파일을 전송시에는 전송타입 변경 필요)
ftpClient.enterLocalPassiveMode();// Active 모드 설정
// ftpClient.changeWorkingDirectory(remoteFilePath);
if (!(ftpClient.changeWorkingDirectory(remoteFilePath))) {//저장파일경로
logger.error("[FTP] Failed to change working directory.");
return;
}
File localFile = new File(localFilePath);//로컬 파일 경로 기반으로 File 객체 생성
fileInputStream = new FileInputStream(localFile);
if (ftpClient.storeFile(localFile.getName(), fileInputStream)){// 전송 - ftp 서버에 파일 업로드
logger.info("[FTP] Image uploaded successfully.");
} else {
logger.error("[FTP] Failed to upload image.");
}
}catch (FileNotFoundException fe){
logger.error("[FTP] File not Found. =>",fe.getMessage());
fe.printStackTrace();
}catch (SocketException se){
logger.error("[FTP] Socket Error. =>",se.getMessage());
se.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try{
if(fileInputStream != null){
fileInputStream.close();
}
//로그아웃
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
⬇️호출
try{
//FTP 서버에 전송
FTPControl.uploadFile(ftpServer,iFtpPort, ftpUsername, ftpPassword, realPath + "/" + strContentImg1New, strFTPImgPath);
} catch(Exception e) {
e.printStackTrace();
}
ftpServer : FTP 서버 IP주소
iFtpPort : 21 (FTP 서버 기존 포트)
ftpUsername: username(계정)
ftpPassword: password(계정)
realPath+"/"+strContentImag1New : 로컬경로/사진명
strFTPImagePath : 리모트 경로 즉, FTP서버 업로드할 저정 경로 ex) /상위경로/하위경로
+
저는 setting.properties파일을 만들어서 거기다가 정보들을 입력하여
정보를 가져오는 방식을 사용했습니다.(이유 : 수정하기 편리하기 위해서)
'◆JAVA > SPRING + JAVA' 카테고리의 다른 글
Spring Framework에서 현재 HTTP 요청 객체(HttpServletRequest)를 얻는 방법 (0) | 2023.09.12 |
---|---|
[Spring+Java]넘어온 값 전체 출력하기 (0) | 2023.02.03 |