FTP伺服器檔案上傳的代碼實現

來源:互聯網
上載者:User

標籤:des   continue   ati   實現   package   hello   final   return   eve   

方式一:

@Test    public void testFtpClient() throws Exception {        // 1、建立一個FtpClient對象        FTPClient ftpClient = new FTPClient();        // 2、建立ftp串連,預設是21連接埠        ftpClient.connect("192.168.1.121", 21);        // 3、登入ftp伺服器,使用使用者名稱和密碼        ftpClient.login("ftpuser", "root");        // 4、上傳檔案        // 讀取本地檔案        FileInputStream inputStream = new FileInputStream(new File("D:\\image\\1.jpg"));        // 設定上傳路徑        ftpClient.changeWorkingDirectory("/home/ftpuser/taotao/images");        // 修改上傳檔案的格式        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);        // 第一個參數:伺服器端文檔名        // 第二個參數:上傳文檔的inputStream        ftpClient.storeFile("hello.jpg", inputStream);        // 5、關閉串連        ftpClient.logout();    }

方式二:

使用FTP工具類FtpUtil

package com.taotao.common.utils;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import org.apache.commons.net.ftp.FTP;import org.apache.commons.net.ftp.FTPClient;import org.apache.commons.net.ftp.FTPFile;import org.apache.commons.net.ftp.FTPReply;/*** @ClassName: FtpUtil* @Description: ftp上傳下載工具類* @author Administrator* @date 2017年8月6日*/public class FtpUtil{    /**     * Description: 向FTP伺服器上傳檔案     *      * @param host FTP伺服器hostname     * @param port FTP伺服器連接埠     * @param username FTP登入帳號     * @param password FTP登入密碼     * @param basePath FTP伺服器基礎目錄     * @param filePath FTP伺服器檔案存放路徑。例如分日期存放:/2017/08/06。檔案的路徑為basePath+filePath     * @param filename 上傳到FTP伺服器上的檔案名稱     * @param input 輸入資料流     * @return 成功返回true,否則返回false     */    public static boolean uploadFile(String host, int port, String username, String password, String basePath,        String filePath, String filename, InputStream input)    {        boolean result = false;        FTPClient ftp = new FTPClient();        try        {            int reply;            ftp.connect(host, port);// 串連FTP伺服器            // 如果採用預設連接埠,可以使用ftp.connect(host)的方式直接連接FTP伺服器            ftp.login(username, password);// 登入            reply = ftp.getReplyCode();            if (!FTPReply.isPositiveCompletion(reply))            {                ftp.disconnect();                return result;            }            // 切換到上傳目錄            if (!ftp.changeWorkingDirectory(basePath + filePath))            {                // 如果目錄不存在建立目錄                String[] dirs = filePath.split("/");                String tempPath = basePath;                for (String dir : dirs)                {                    if (null == dir || "".equals(dir))                        continue;                    tempPath += "/" + dir;                    if (!ftp.changeWorkingDirectory(tempPath))                    {                        if (!ftp.makeDirectory(tempPath))                        {                            return result;                        }                        else                        {                            ftp.changeWorkingDirectory(tempPath);                        }                    }                }            }            // 設定上傳檔案的類型為二進位類型            ftp.setFileType(FTP.BINARY_FILE_TYPE);            // 上傳檔案            if (!ftp.storeFile(filename, input))            {                return result;            }            input.close();            ftp.logout();            result = true;        }        catch (IOException e)        {            e.printStackTrace();        }        finally        {            if (ftp.isConnected())            {                try                {                    ftp.disconnect();                }                catch (IOException ioe)                {                }            }        }        return result;    }        /**     * Description: 從FTP伺服器下載檔案     *      * @param host FTP伺服器hostname     * @param port FTP伺服器連接埠     * @param username FTP登入帳號     * @param password FTP登入密碼     * @param remotePath FTP伺服器上的相對路徑     * @param fileName 要下載的檔案名稱     * @param localPath 下載後儲存到本地的路徑     * @return     */    public static boolean downloadFile(String host, int port, String username, String password, String remotePath,        String fileName, String localPath)    {        boolean result = false;        FTPClient ftp = new FTPClient();        try        {            int reply;            ftp.connect(host, port);            // 如果採用預設連接埠,可以使用ftp.connect(host)的方式直接連接FTP伺服器            ftp.login(username, password);// 登入            reply = ftp.getReplyCode();            if (!FTPReply.isPositiveCompletion(reply))            {                ftp.disconnect();                return result;            }            ftp.changeWorkingDirectory(remotePath);// 轉移到FTP伺服器目錄            FTPFile[] fs = ftp.listFiles();            for (FTPFile ff : fs)            {                if (ff.getName().equals(fileName))                {                    File localFile = new File(localPath + "/" + ff.getName());                                        OutputStream is = new FileOutputStream(localFile);                    ftp.retrieveFile(ff.getName(), is);                    is.close();                }            }            ftp.logout();            result = true;        }        catch (IOException e)        {            e.printStackTrace();        }        finally        {            if (ftp.isConnected())            {                try                {                    ftp.disconnect();                }                catch (IOException ioe)                {                }            }        }        return result;    }}

測試載入器類:

@Test    public void testFtpUtil() throws Exception {        // 讀取本地檔案        FileInputStream inputStream = new FileInputStream(new File("D:\\image\\11.jpg"));        FtpUtil.uploadFile("192.168.1.121", 21, "ftpuser", "root", "/home/ftpuser/taotao/images", "/2017/08/06", "11.jpg", inputStream);    }

 

FTP伺服器檔案上傳的代碼實現

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.