SpringBoot整合FTP使用示例教程
更新時間:2024年08月13日 10:57:54 作者:Charge8
這篇文章主要介紹了SpringBoot整合FTP使用示例教程,本文通過示例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
一、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ù)器的端口號(連接端口號) */ @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ù)器,以及上傳和上傳都必須要用到一個對象) */ try { FTPClient ftpClient = new FTPClient(); /** * 連接 FTP服務(wù) */ // 設(shè)置編碼 ftpClient.setControlEncoding("UTF-8"); // 設(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ù),用戶名或密碼錯誤"); // 連接失敗,斷開連接 ftpClient.disconnect(); return null; } else { log.info("連接到FTP服務(wù)成功"); // 設(shè)置二進(jìn)制方式傳輸文件 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 設(shè)置被動工作模式,文件傳輸端口設(shè)置,否則文件上傳不成功,也不報錯 ftpClient.enterLocalPassiveMode(); } return ftpClient; } catch (SocketException e) { e.printStackTrace(); log.error("FTP的IP地址錯誤,請正確配置。"); } catch (IOException e) { e.printStackTrace(); log.error("FTP的端口錯誤,請正確配置。"); } 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 需要創(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é)果是一樣的,都會到用戶的根目錄下。推薦顯示指定。 * FTP服務(wù)會判斷文件夾已存在,不會創(chuàng)建,不存在,則會創(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 上傳的文件存儲目錄 * @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)建文件存儲目錄 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工具類測試
在項目,通常我們提供一個 FtpService實現(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)文章
Struts2中接收表單數(shù)據(jù)的三種驅(qū)動方式
這篇文章簡單給大家介紹了Struts2中接收表單數(shù)據(jù)的三種驅(qū)動方式,非常不錯,具有參考借鑒價值,需要的的朋友參考下吧2017-07-07go語言題解LeetCode88合并兩個有序數(shù)組示例
這篇文章主要為大家介紹了go語言題解LeetCode88合并兩個有序數(shù)組示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12