最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot整合FTP使用示例教程

 更新時間:2024年08月13日 10:57:54   作者:Charge8  
這篇文章主要介紹了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配置信息。

# 文件上傳相關
file:
  # FTP文件相關
  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服務器的地址
     */
    @Value("${file.ftp.host}")
    private String ftpHost;
    /**
     * ftp服務器的端口號(連接端口號)
     */
    @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服務工具類

/**
 * FTP服務工具類
 */
@Slf4j
public class FtpUtils {
    /**
     * 獲取 FTPClient對象
     *
     * @param ftpHost     FTP主機服務器
     * @param ftpPort     FTP端口 默認為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服務器,以及上傳和上傳都必須要用到一個對象)
         */
        try {
            FTPClient ftpClient = new FTPClient();
            /**
             * 連接 FTP服務
             */
            // 設置編碼
            ftpClient.setControlEncoding("UTF-8");
            // 設置連接超時時間(單位:毫秒)
            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服務,用戶名或密碼錯誤");
                // 連接失敗,斷開連接
                ftpClient.disconnect();
                return null;
            } else {
                log.info("連接到FTP服務成功");
                // 設置二進制方式傳輸文件
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                // 設置被動工作模式,文件傳輸端口設置,否則文件上傳不成功,也不報錯
                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("關閉ftp客戶端成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("關閉ftp客戶端異常");
        }
    }
    /**
     * 創(chuàng)建文件夾
     *
     * @param ftpHost     FTP主機服務器
     * @param ftpPort     FTP端口 默認為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的服務器路徑。
             * FTP服務為FTP虛擬用戶默認了根目錄,所以我們可以切換也可以不切換,結果是一樣的,都會到用戶的根目錄下。推薦顯示指定。
             * FTP服務會判斷文件夾已存在,不會創(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主機服務器
     * @param ftpPort     FTP端口 默認為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("關閉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服務
     *
     * @param ftpHost     FTP主機服務器
     * @param ftpPort     FTP端口 默認為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);
            // 設置文件類型為二進制方式傳輸文件
            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服務失敗:{}", e);
        } finally {
            closeConnect(ftpClient);
        }
        return result;
    }
    /**
     * 從FTP中獲取文件的輸入流
     *
     * @param ftpHost     FTP主機服務器
     * @param ftpPort     FTP端口 默認為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主機服務器
     * @param ftpPort     FTP端口 默認為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服務工具類。

這里進行 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服務
        //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文件結果,result={}", result);
    }

在這里插入圖片描述

到此這篇關于SpringBoot整合FTP使用的文章就介紹到這了,更多相關SpringBoot整合FTP內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • mybatis分頁效果實現(xiàn)代碼

    mybatis分頁效果實現(xiàn)代碼

    這篇文章主要為大家詳細介紹了mybatis分頁效果的實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • idea切換分支的時候,忽略一些無用的修改設置

    idea切換分支的時候,忽略一些無用的修改設置

    這篇文章主要介紹了idea切換分支的時候,忽略一些無用的修改操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • Java類中this關鍵字與static關鍵字的用法解析

    Java類中this關鍵字與static關鍵字的用法解析

    這篇文章主要介紹了Java類中this關鍵字與static關鍵字的用法解析,文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-09-09
  • Java(Springboot)項目調用第三方WebService接口實現(xiàn)代碼

    Java(Springboot)項目調用第三方WebService接口實現(xiàn)代碼

    這篇文章主要介紹了如何使用Java調用WebService接口,傳遞XML參數(shù),獲取XML響應,并將其解析為JSON格式,文中詳細描述了WSDL文檔的使用、HttpClientBuilder和Apache?Axis兩種調用方式的具體實現(xiàn)步驟,需要的朋友可以參考下
    2025-02-02
  • Spring?c3p0配置的實現(xiàn)示例

    Spring?c3p0配置的實現(xiàn)示例

    在Spring框架中配置c3p0連接池可以提升數(shù)據(jù)庫操作性能,本文主要介紹了Spring?c3p0配置的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下
    2024-09-09
  • java中多線程與線程池的基本使用方法

    java中多線程與線程池的基本使用方法

    在Java中,我們可以利用多線程來最大化地壓榨CPU多核計算的能力,下面這篇文章主要給大家介紹了關于java中多線程與線程池基本使用的相關資料,需要的朋友可以參考下
    2021-09-09
  • 詳解Java Web項目啟動執(zhí)行順序

    詳解Java Web項目啟動執(zhí)行順序

    這篇文章主要介紹了詳解Java Web項目啟動執(zhí)行順序,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-06-06
  • 完美解決java double數(shù)相加和相減的方案

    完美解決java double數(shù)相加和相減的方案

    這篇文章主要介紹了完美解決java double數(shù)相加和相減的方案,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-01-01
  • Java使用agent實現(xiàn)main方法之前的實例詳解

    Java使用agent實現(xiàn)main方法之前的實例詳解

    這篇文章主要介紹了Java使用agent實現(xiàn)main方法之前的實例詳解的相關資料,希望通過本文能幫助到大家,讓大家理解這部分內容,需要的朋友可以參考下
    2017-10-10
  • Spring導入properties配置文件代碼示例

    Spring導入properties配置文件代碼示例

    這篇文章主要介紹了Spring導入properties配置文件代碼示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-10-10

最新評論

孙吴县| 勃利县| 留坝县| 唐海县| 屯门区| 万山特区| 潞城市| 龙江县| 泸溪县| 枣阳市| 彭阳县| 安义县| 肃宁县| 普定县| 常德市| 常州市| 建湖县| 兰坪| 昌吉市| 襄汾县| 永宁县| 长丰县| 乌恰县| 宿州市| 镇巴县| 福州市| 石屏县| 高尔夫| 固镇县| 双流县| 西盟| 烟台市| 遂宁市| 民丰县| 长春市| 宝丰县| 沙河市| 甘南县| 济阳县| 兰考县| 万州区|