SpringBoot整合FTP使用示例教程
一、SpringBoot整合FTP使用
1、引入依賴
這里引用 Apache commons-net依賴,用于FTP客戶端操作。
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.11.0</version>
</dependency>2、FTP配置信息類
(1)配置文件添加 ftp配置信息。
# 文件上傳相關(guān)
file:
# FTP文件相關(guān)
ftp:
host: 192.168.xxx.xxx
port: 21
username: zhangsan
password: xxxxxx
basePath: /ftpv
filePathPrefix: http://192.168.xxx.xxx:9090/viewFile(2)ftp自定義配置信息類
/**
* ftp自定義配置信息類
*/
@Data
@Configuration
public class FtpProperties {
/**
* ftp服務(wù)器的地址
*/
@Value("${file.ftp.host}")
private String ftpHost;
/**
* ftp服務(wù)器的端口號(hào)(連接端口號(hào))
*/
@Value("${file.ftp.port}")
private int ftpPort;
/**
* ftp的用戶名
*/
@Value("${file.ftp.username}")
private String ftpUsername;
/**
* ftp的密碼
*/
@Value("${file.ftp.password}")
private String ftpPassword;
/**
* ftp用戶上傳的根目錄
*/
@Value("${file.ftp.basePath}")
private String ftpBasePath;
/**
* http訪問文件的路徑前綴,配合Nginx靜態(tài)資源訪問
*/
@Value("${file.ftp.filePathPrefix}")
private String ftpFilePathPrefix;
}3、FTP服務(wù)工具類
/**
* FTP服務(wù)工具類
*/
@Slf4j
public class FtpUtils {
/**
* 獲取 FTPClient對象
*
* @param ftpHost FTP主機(jī)服務(wù)器
* @param ftpPort FTP端口 默認(rèn)為21
* @param ftpUserName FTP 登錄密碼
* @param ftpPassword FTP登錄密碼
* @return FTPClient對象
*/
private static FTPClient getFTPClient(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword) {
/**
* 創(chuàng)建 FTPClient對象(對于連接ftp服務(wù)器,以及上傳和上傳都必須要用到一個(gè)對象)
*/
try {
FTPClient ftpClient = new FTPClient();
/**
* 連接 FTP服務(wù)
*/
// 設(shè)置編碼
ftpClient.setControlEncoding("UTF-8");
// 設(shè)置連接超時(shí)時(shí)間(單位:毫秒)
ftpClient.setConnectTimeout(10 * 1000);
// 連接
ftpClient.connect(ftpHost, ftpPort);
// 登錄
ftpClient.login(ftpUserName, ftpPassword);
/**
* ftpClient.getReplyCode():接受狀態(tài)碼(如果成功,返回230,如果失敗返回503)
* FTPReply.isPositiveCompletion():如果連接成功返回true,否則返回false
*/
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
log.error("未連接到FTP服務(wù),用戶名或密碼錯(cuò)誤");
// 連接失敗,斷開連接
ftpClient.disconnect();
return null;
} else {
log.info("連接到FTP服務(wù)成功");
// 設(shè)置二進(jìn)制方式傳輸文件
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// 設(shè)置被動(dòng)工作模式,文件傳輸端口設(shè)置,否則文件上傳不成功,也不報(bào)錯(cuò)
ftpClient.enterLocalPassiveMode();
}
return ftpClient;
} catch (SocketException e) {
e.printStackTrace();
log.error("FTP的IP地址錯(cuò)誤,請正確配置。");
} catch (IOException e) {
e.printStackTrace();
log.error("FTP的端口錯(cuò)誤,請正確配置。");
} catch (Exception e) {
e.printStackTrace();
log.error("獲取ftp客戶端異常");
}
return null;
}
/**
* 斷開 FTPClient對象
*/
private static void closeConnect(FTPClient ftpClient) {
try {
if (ftpClient != null && ftpClient.isConnected()) {
ftpClient.logout();
// 斷開ftp的連接
ftpClient.disconnect();
log.info("關(guān)閉ftp客戶端成功");
}
} catch (Exception e) {
e.printStackTrace();
log.error("關(guān)閉ftp客戶端異常");
}
}
/**
* 創(chuàng)建文件夾
*
* @param ftpHost FTP主機(jī)服務(wù)器
* @param ftpPort FTP端口 默認(rèn)為21
* @param ftpUserName FTP 登錄密碼
* @param ftpPassword FTP登錄密碼
* @param ftpBasePath FTP用戶上傳的根目錄
* @param dirPath 需要?jiǎng)?chuàng)建的文件夾,多層使用/隔開
* @return
*/
public static boolean createDirectory(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String ftpBasePath, String dirPath) {
FTPClient ftpClient = FtpUtils.getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
try {
/**
* 切換到ftp的服務(wù)器路徑。
* FTP服務(wù)為FTP虛擬用戶默認(rèn)了根目錄,所以我們可以切換也可以不切換,結(jié)果是一樣的,都會(huì)到用戶的根目錄下。推薦顯示指定。
* FTP服務(wù)會(huì)判斷文件夾已存在,不會(huì)創(chuàng)建,不存在,則會(huì)創(chuàng)建。
*/
ftpClient.changeWorkingDirectory(ftpBasePath);
if (StringUtils.isBlank(dirPath)) {
return false;
}
String[] dirPathArr = dirPath.split("/");
for (String dir : dirPathArr) {
if (StringUtils.isNotBlank(dir)) {
ftpClient.makeDirectory(dir);
// 切換到ftp的創(chuàng)建目錄
ftpClient.changeWorkingDirectory(dir);
}
}
return true;
} catch (IOException e) {
e.printStackTrace();
log.error("創(chuàng)建文件夾異常");
} finally {
closeConnect(ftpClient);
}
return false;
}
/**
* 查詢指定路徑下的所有文件的文件名
*
* @param ftpHost FTP主機(jī)服務(wù)器
* @param ftpPort FTP端口 默認(rèn)為21
* @param ftpUserName FTP 登錄密碼
* @param ftpPassword FTP登錄密碼
* @param dirPath 查詢指定路徑
* @return
*/
public static List<String> listFileName(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String dirPath) {
if (StringUtils.isBlank(dirPath)) {
return null;
}
FTPClient ftpClient = FtpUtils.getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
// 獲得指定目錄下所有文件名
FTPFile[] ftpFiles = null;
try {
//ftpClient.enterLocalPassiveMode(); // 列出路徑下的所有文件的文件名
ftpFiles = ftpClient.listFiles(dirPath);
} catch (IOException e) {
e.printStackTrace();
log.info("關(guān)閉ftp客戶端成功");
return null;
} finally {
closeConnect(ftpClient);
}
List<String> fileNameList = new LinkedList<String>();
for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
FTPFile file = ftpFiles[i];
if (file.isFile()) {
fileNameList.add(file.getName());
}
}
return fileNameList;
}
/**
* 上傳文件到ftp服務(wù)
*
* @param ftpHost FTP主機(jī)服務(wù)器
* @param ftpPort FTP端口 默認(rèn)為21
* @param ftpUserName FTP 登錄密碼
* @param ftpPassword FTP登錄密碼
* @param ftpBasePath FTP用戶上傳的根目錄
* @param fileDirPath 上傳的文件存儲(chǔ)目錄
* @param fileName 上傳的文件名
* @param is 上傳的文件輸入流
*/
public static boolean uploadFileToFtp(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String ftpBasePath, String fileDirPath, String fileName, InputStream is) {
FTPClient ftpClient = FtpUtils.getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
boolean result = false;
try {
// 創(chuàng)建文件存儲(chǔ)目錄
FtpUtils.createDirectory(ftpHost, ftpPort, ftpUserName, ftpPassword, ftpBasePath, fileDirPath);
// 切換到ftp的文件目錄,即文件上傳目錄
ftpClient.changeWorkingDirectory(fileDirPath);
ftpClient.setControlEncoding("UTF-8");
ftpClient.setBufferSize(1024 * 10);
// 設(shè)置文件類型為二進(jìn)制方式傳輸文件
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.setDefaultTimeout(18000);
ftpClient.setConnectTimeout(6000);
ftpClient.setSoTimeout(6000);
result = ftpClient.storeFile(fileName, is);
} catch (IOException e) {
log.error("上傳文件到ftp服務(wù)失敗:{}", e);
} finally {
closeConnect(ftpClient);
}
return result;
}
/**
* 從FTP中獲取文件的輸入流
*
* @param ftpHost FTP主機(jī)服務(wù)器
* @param ftpPort FTP端口 默認(rèn)為21
* @param ftpUserName FTP 登錄密碼
* @param ftpPassword FTP登錄密碼
* @param ftpFilePath ftp文件路徑,根目錄開始
* @return
*/
public static InputStream getInputStreamOfFtpFile(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String ftpFilePath) {
FTPClient ftpClient = FtpUtils.getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
InputStream is = null;
try {
is = ftpClient.retrieveFileStream(ftpFilePath);
} catch (IOException e) {
e.printStackTrace();
log.error("獲取文件輸入流異常");
} finally {
closeConnect(ftpClient);
}
return is;
}
/**
* 刪除ftp文件
*
* @param ftpHost FTP主機(jī)服務(wù)器
* @param ftpPort FTP端口 默認(rèn)為21
* @param ftpUserName FTP 登錄密碼
* @param ftpPassword FTP登錄密碼
* @param ftpFilePath ftp文件路徑,根目錄開始
* @return
*/
public static boolean deleteFtpFile(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String ftpFilePath) {
FTPClient ftpClient = FtpUtils.getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
boolean result = false;
try {
result = ftpClient.deleteFile(ftpFilePath);
} catch (IOException e) {
log.error("刪除ftp文件失敗:{}", e);
} finally {
closeConnect(ftpClient);
}
return result;
}
}4、FTP工具類測試
在項(xiàng)目,通常我們提供一個(gè) FtpService實(shí)現(xiàn)類來封裝 FTP服務(wù)工具類。
這里進(jìn)行 FTP工具類測試即可。
public static void main(String[] args) throws Exception {
FtpProperties ftpProperties = getFtpProperties();
獲取 FTPClient對象
//FTPClient ftpClient = FtpUtils.getFTPClient(ftpProperties.getFtpHost(), ftpProperties.getFtpPort(), ftpProperties.getFtpUsername(), ftpProperties.getFtpPassword());
斷開 FTPClient對象
//FtpUtils.closeConnect(ftpClient);
// 創(chuàng)建文件夾
//String dirPath = "dev_dir1/d11/d12";
//FtpUtils.createDirectory(ftpProperties.getFtpHost(), ftpProperties.getFtpPort(), ftpProperties.getFtpUsername(), ftpProperties.getFtpPassword(), ftpProperties.getFtpBasePath(), dirPath);
// 查詢指定路徑下的所有文件的文件名
//String dirPath = "/dev_dir1";
//List<String> fileNameList = FtpUtils.listFileName(ftpProperties.getFtpHost(), ftpProperties.getFtpPort(), ftpProperties.getFtpUsername(), ftpProperties.getFtpPassword(), dirPath);
//for (String fileName : Optional.ofNullable(fileNameList).orElse(new ArrayList<>())) {
// System.out.println(fileName);
//}
// 上傳文件到ftp服務(wù)
//String fileDirPath = "dev_dir1";
//String fileName = "dev_uploadFile001.jpg";
//InputStream is = new FileInputStream("D:\\TempFiles\\598a80e12f9ad-中文.jpg");
//FtpUtils.uploadFileToFtp(ftpProperties.getFtpHost(), ftpProperties.getFtpPort(), ftpProperties.getFtpUsername(), ftpProperties.getFtpPassword(), ftpProperties.getFtpBasePath(), fileDirPath, fileName, is);
// 從FTP中獲取文件的輸入流
//String ftpFilePath = "dev_dir1/dev_uploadFile001.jpg";
//InputStream inputStreamOfFtpFile = FtpUtils.getInputStreamOfFtpFile(ftpProperties.getFtpHost(), ftpProperties.getFtpPort(), ftpProperties.getFtpUsername(), ftpProperties.getFtpPassword(), ftpFilePath);
//FileUtils.copyInputStreamToFile(inputStreamOfFtpFile, new File("D:\\TempFiles\\dev_uploadFile001.jpg"));
//String ftpFilePath = "dev_dir1/zs_111.txt";
//InputStream inputStreamOfFtpFile = FtpUtils.getInputStreamOfFtpFile(ftpProperties.getFtpHost(), ftpProperties.getFtpPort(), ftpProperties.getFtpUsername(), ftpProperties.getFtpPassword(), ftpFilePath);
//FileUtils.copyInputStreamToFile(inputStreamOfFtpFile, new File("D:\\TempFiles\\zs_111.txt"));
// 刪除ftp文件
String ftpFilePath = "dev_dir1/dev_uploadFile002.jpg";
boolean result = FtpUtils.deleteFtpFile(ftpProperties.getFtpHost(), ftpProperties.getFtpPort(), ftpProperties.getFtpUsername(), ftpProperties.getFtpPassword(), ftpFilePath);
log.info("刪除ftp文件結(jié)果,result={}", result);
}

到此這篇關(guān)于SpringBoot整合FTP使用的文章就介紹到這了,更多相關(guān)SpringBoot整合FTP內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
idea切換分支的時(shí)候,忽略一些無用的修改設(shè)置
這篇文章主要介紹了idea切換分支的時(shí)候,忽略一些無用的修改操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02
Java類中this關(guān)鍵字與static關(guān)鍵字的用法解析
這篇文章主要介紹了Java類中this關(guān)鍵字與static關(guān)鍵字的用法解析,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09
Java(Springboot)項(xiàng)目調(diào)用第三方WebService接口實(shí)現(xiàn)代碼
這篇文章主要介紹了如何使用Java調(diào)用WebService接口,傳遞XML參數(shù),獲取XML響應(yīng),并將其解析為JSON格式,文中詳細(xì)描述了WSDL文檔的使用、HttpClientBuilder和Apache?Axis兩種調(diào)用方式的具體實(shí)現(xiàn)步驟,需要的朋友可以參考下2025-02-02
詳解Java Web項(xiàng)目啟動(dòng)執(zhí)行順序
這篇文章主要介紹了詳解Java Web項(xiàng)目啟動(dòng)執(zhí)行順序,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-06-06
Java使用agent實(shí)現(xiàn)main方法之前的實(shí)例詳解
這篇文章主要介紹了Java使用agent實(shí)現(xiàn)main方法之前的實(shí)例詳解的相關(guān)資料,希望通過本文能幫助到大家,讓大家理解這部分內(nèi)容,需要的朋友可以參考下2017-10-10
Spring導(dǎo)入properties配置文件代碼示例
這篇文章主要介紹了Spring導(dǎo)入properties配置文件代碼示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10

