溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringBoot項目如何集成FTP

發(fā)布時間:2021-10-28 13:32:01 來源:億速云 閱讀:150 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下SpringBoot項目如何集成FTP,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

    FTP相關(guān)軟件安裝

    我在此就不介紹如何安裝FTP了,但是我可以推薦給大家一些軟件作為選擇。
    Linux版本,推薦使用vsftpd進(jìn)行搭建FTP,只需要改指定的幾個配置,添加上用戶即可。
    Windows版本,推薦使用Serv-U進(jìn)行搭建FTP,圖形化界面,有中文版,操作起來很簡單。

    開始集成

    引入相關(guān)jar包

    這里我們對FTP相關(guān)的組件包使用的是edtFTPj,其實之前很多人都選擇的是Java自帶的包來實現(xiàn)FTP功能的。
    在我們的SpringBoot項目中pom.xml下添加以下依賴。

    <dependency>
        <groupId>com.enterprisedt</groupId>
        <artifactId>edtFTPj</artifactId>
        <version>1.5.3</version>
    </dependency>

    更新maven進(jìn)行引入,然后我們進(jìn)行下一步。

    引入FTPUtils.java和FTPHelper.java

    引入兩個工具類。

    我這里先貢獻(xiàn)一下代碼,請大家酌情作為參考。

    /**
     * Ftp 工具類
     */
    public class FtpHelper {
    
        private FTPClient ftp;
    
        public FtpHelper() {
    
        }
    
        /**
         * 初始化Ftp信息
         *
         * @param ftpServer   ftp服務(wù)器地址
         * @param ftpPort     Ftp端口號
         * @param ftpUsername ftp 用戶名
         * @param ftpPassword ftp 密碼
         */
        public FtpHelper(String ftpServer, int ftpPort, String ftpUsername,
                         String ftpPassword) {
            connect(ftpServer, ftpPort, ftpUsername, ftpPassword);
        }
    
        /**
         * 連接到ftp
         *
         * @param ftpServer   ftp服務(wù)器地址
         * @param ftpPort     Ftp端口號
         * @param ftpUsername ftp 用戶名
         * @param ftpPassword ftp 密碼
         */
        public void connect(String ftpServer, int ftpPort, String ftpUsername, String ftpPassword) {
            ftp = new FTPClient();
            try {
                ftp.setControlEncoding("UTF-8");
                ftp.setRemoteHost(ftpServer);
                ftp.setRemotePort(ftpPort);
                ftp.setTimeout(6000);
                ftp.setConnectMode(FTPConnectMode.ACTIVE);
                ftp.connect();
                ftp.login(ftpUsername, ftpPassword);
                ftp.setType(FTPTransferType.BINARY);
            } catch (Exception e) {
                e.printStackTrace();
                ftp = null;
            }
        }
    
        /**
         * 更改ftp路徑
         *
         * @param ftp
         * @param dirName
         * @return
         */
        public boolean checkDirectory(FTPClient ftp, String dirName) {
            boolean flag;
            try {
                ftp.chdir(dirName);
                flag = true;
            } catch (Exception e) {
                e.printStackTrace();
                flag = false;
            }
            return flag;
        }
    
        /**
         * 斷開ftp鏈接
         */
        public void disconnect() {
            try {
                if (ftp.connected()) {
                    ftp.quit();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 讀取ftp文件流
         *
         * @param filePath ftp文件路徑
         * @return s
         * @throws Exception
         */
        public InputStream downloadFile(String filePath) throws Exception {
            InputStream inputStream = null;
            String fileName = "";
            filePath = StringUtils.removeStart(filePath, "/");
            int len = filePath.lastIndexOf("/");
            if (len == -1) {
                if (filePath.length() > 0) {
                    fileName = filePath;
                } else {
                    throw new Exception("沒有輸入文件路徑");
                }
            } else {
                fileName = filePath.substring(len + 1);
    
                String type = filePath.substring(0, len);
                String[] typeArray = type.split("/");
                for (String s : typeArray) {
                    ftp.chdir(s);
                }
            }
            byte[] data;
            try {
                data = ftp.get(fileName);
                inputStream = new ByteArrayInputStream(data);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return inputStream;
        }
    
        /**
         * 上傳文件到ftp
         *
         * @param file     文件對象
         * @param filePath 上傳的路徑
         * @throws Exception
         */
        public void uploadFile(File file, String filePath) throws Exception {
            InputStream inStream = new FileInputStream(file);
            uploadFile(inStream, filePath);
        }
    
        /**
         * 上傳文件到ftp
         *
         * @param inStream 上傳的文件流
         * @param filePath 上傳路徑
         * @throws Exception
         */
        public void uploadFile(InputStream inStream, String filePath)
                throws Exception {
            if (inStream == null) {
                return;
            }
            String fileName = "";
            filePath = StringUtils.removeStart(filePath, "/");
            int len = filePath.lastIndexOf("/");
            if (len == -1) {
                if (filePath.length() > 0) {
                    fileName = filePath;
                } else {
                    throw new Exception("沒有輸入文件路徑");
                }
            } else {
                fileName = filePath.substring(len + 1);
                String type = filePath.substring(0, len);
                String[] typeArray = type.split("/");
                for (String s : typeArray) {
                    if (!checkDirectory(ftp, s)) {
                        ftp.mkdir(s);
                    }
                }
            }
            ftp.put(inStream, fileName);
        }
    
        /**
         * 刪除ftp文件
         *
         * @param filePath 文件路徑
         * @throws Exception
         */
        public void deleteFile(String filePath) throws Exception {
            String fileName = "";
            filePath = StringUtils.removeStart(filePath, "/");
            int len = filePath.lastIndexOf("/");
            if (len == -1) {
                if (filePath.length() > 0) {
                    fileName = filePath;
                } else {
                    throw new Exception("沒有輸入文件路徑");
                }
            } else {
                fileName = filePath.substring(len + 1);
    
                String type = filePath.substring(0, len);
                String[] typeArray = type.split("/");
                for (String s : typeArray) {
                    if (checkDirectory(ftp, s)) {
                        ftp.chdir(s);
                    }
                }
            }
            ftp.delete(fileName);
        }
    
        /**
         * 切換目錄
         *
         * @param path
         * @throws Exception
         */
        public void changeDirectory(String path) {
            if (!ValidateUtils.isEmpty(path)) {
                try {
                    ftp.chdir(path);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * Ftp 工具類
     */
    public class FtpHelper {
    
        private FTPClient ftp;
    
        public FtpHelper() {
    
        }
    
        /**
         * 初始化Ftp信息
         *
         * @param ftpServer   ftp服務(wù)器地址
         * @param ftpPort     Ftp端口號
         * @param ftpUsername ftp 用戶名
         * @param ftpPassword ftp 密碼
         */
        public FtpHelper(String ftpServer, int ftpPort, String ftpUsername,
                         String ftpPassword) {
            connect(ftpServer, ftpPort, ftpUsername, ftpPassword);
        }
    
        /**
         * 連接到ftp
         *
         * @param ftpServer   ftp服務(wù)器地址
         * @param ftpPort     Ftp端口號
         * @param ftpUsername ftp 用戶名
         * @param ftpPassword ftp 密碼
         */
        public void connect(String ftpServer, int ftpPort, String ftpUsername, String ftpPassword) {
            ftp = new FTPClient();
            try {
                ftp.setControlEncoding("UTF-8");
                ftp.setRemoteHost(ftpServer);
                ftp.setRemotePort(ftpPort);
                ftp.setTimeout(6000);
                ftp.setConnectMode(FTPConnectMode.ACTIVE);
                ftp.connect();
                ftp.login(ftpUsername, ftpPassword);
                ftp.setType(FTPTransferType.BINARY);
            } catch (Exception e) {
                e.printStackTrace();
                ftp = null;
            }
        }
    
        /**
         * 更改ftp路徑
         *
         * @param ftp
         * @param dirName
         * @return
         */
        public boolean checkDirectory(FTPClient ftp, String dirName) {
            boolean flag;
            try {
                ftp.chdir(dirName);
                flag = true;
            } catch (Exception e) {
                e.printStackTrace();
                flag = false;
            }
            return flag;
        }
    
        /**
         * 斷開ftp鏈接
         */
        public void disconnect() {
            try {
                if (ftp.connected()) {
                    ftp.quit();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 讀取ftp文件流
         *
         * @param filePath ftp文件路徑
         * @return s
         * @throws Exception
         */
        public InputStream downloadFile(String filePath) throws Exception {
            InputStream inputStream = null;
            String fileName = "";
            filePath = StringUtils.removeStart(filePath, "/");
            int len = filePath.lastIndexOf("/");
            if (len == -1) {
                if (filePath.length() > 0) {
                    fileName = filePath;
                } else {
                    throw new Exception("沒有輸入文件路徑");
                }
            } else {
                fileName = filePath.substring(len + 1);
    
                String type = filePath.substring(0, len);
                String[] typeArray = type.split("/");
                for (String s : typeArray) {
                    ftp.chdir(s);
                }
            }
            byte[] data;
            try {
                data = ftp.get(fileName);
                inputStream = new ByteArrayInputStream(data);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return inputStream;
        }
    
        /**
         * 上傳文件到ftp
         *
         * @param file     文件對象
         * @param filePath 上傳的路徑
         * @throws Exception
         */
        public void uploadFile(File file, String filePath) throws Exception {
            InputStream inStream = new FileInputStream(file);
            uploadFile(inStream, filePath);
        }
    
        /**
         * 上傳文件到ftp
         *
         * @param inStream 上傳的文件流
         * @param filePath 上傳路徑
         * @throws Exception
         */
        public void uploadFile(InputStream inStream, String filePath)
                throws Exception {
            if (inStream == null) {
                return;
            }
            String fileName = "";
            filePath = StringUtils.removeStart(filePath, "/");
            int len = filePath.lastIndexOf("/");
            if (len == -1) {
                if (filePath.length() > 0) {
                    fileName = filePath;
                } else {
                    throw new Exception("沒有輸入文件路徑");
                }
            } else {
                fileName = filePath.substring(len + 1);
                String type = filePath.substring(0, len);
                String[] typeArray = type.split("/");
                for (String s : typeArray) {
                    if (!checkDirectory(ftp, s)) {
                        ftp.mkdir(s);
                    }
                }
            }
            ftp.put(inStream, fileName);
        }
    
        /**
         * 刪除ftp文件
         *
         * @param filePath 文件路徑
         * @throws Exception
         */
        public void deleteFile(String filePath) throws Exception {
            String fileName = "";
            filePath = StringUtils.removeStart(filePath, "/");
            int len = filePath.lastIndexOf("/");
            if (len == -1) {
                if (filePath.length() > 0) {
                    fileName = filePath;
                } else {
                    throw new Exception("沒有輸入文件路徑");
                }
            } else {
                fileName = filePath.substring(len + 1);
    
                String type = filePath.substring(0, len);
                String[] typeArray = type.split("/");
                for (String s : typeArray) {
                    if (checkDirectory(ftp, s)) {
                        ftp.chdir(s);
                    }
                }
            }
            ftp.delete(fileName);
        }
    
        /**
         * 切換目錄
         *
         * @param path
         * @throws Exception
         */
        public void changeDirectory(String path) {
            if (!ValidateUtils.isEmpty(path)) {
                try {
                    ftp.chdir(path);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    如何使用

    public static void main(String[] args) {
            try {
                // 從ftp下載文件
                FtpHelper ftp = new FtpHelper("127.0.0.1", 21, "root", "123456");
                File file = new File("D:\1.doc");
                ftp.uploadFile(file, "test/weradsfad2.doc");
                ftp.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    看完了這篇文章,相信你對“SpringBoot項目如何集成FTP”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI