1. 程式人生 > >使用FTP上傳圖片到圖片伺服器

使用FTP上傳圖片到圖片伺服器

一匯入依賴

            <dependency>
                <groupId>commons-net</groupId>
                <artifactId>commons-net</artifactId>
                <version>${commons-net.version}</version>
            </dependency>

一工具類

/** 
     * Description: 向FTP伺服器上傳檔案 
     * @param
host FTP伺服器hostname * @param port FTP伺服器埠 * @param username FTP登入賬號 * @param password FTP登入密碼 * @param basePath FTP伺服器基礎目錄 * @param filePath FTP伺服器檔案存放路徑。例如分日期存放:/2015/01/01。檔案的路徑為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; }

三測試

    public static void main(String[] args) {
        try {  
            FileInputStream in=new FileInputStream(new File("D:\\temp\\image\\gaigeming.jpg"));  
            boolean flag = uploadFile("192.168.25.133", 21, "ftpuser", "ftpuser", "/home/ftpuser/www/images","/2015/01/21", "gaigeming.jpg", in);  
            System.out.println(flag);  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        }  
    }
}

四:可能出現問題
ftp .storeFile返回false,本地測試可以,部署到伺服器不可以?
解決方法:
在執行ftp .storeFile()之前設定上傳模式:ftp.enterLocalPassiveMode();
ftp連線方式/
主動 FTP : 命令連線:客戶端 >1024 埠 -> 伺服器 21 埠 資料連線:客戶端 >1024 埠 <- 伺服器 20 埠
被動 FTP : 命令連線:客戶端 >1024 埠 -> 伺服器 21 埠 資料連線:客戶端 >1024 埠 -> 伺服器 >1024 埠
FTP協議有兩種工作方式:PORT方式和PASV方式,中文意思為主動式和被動式。
PORT(主動)方式的連線過程是:客戶端向伺服器的FTP埠(預設是21)傳送連線請求,伺服器接受連線,建立一條命令鏈路。當需要傳送資料時, 客戶端在命令鏈路上用PORT命令告訴伺服器:“我打開了***X埠,你過來連線我”。於是伺服器從20埠向客戶端的***X埠傳送連線請求,建立 一條資料鏈路來傳送資料。
PASV(被動)方式的連線過程是:客戶端向伺服器的FTP埠(預設是21)傳送連線請求,伺服器接受連線,建立一條命令鏈路。當需要傳送資料時, 伺服器在命令鏈路上用PASV命令告訴客戶端:“我打開了***X埠,你過來連線我”。於是客戶端向伺服器的***X埠傳送連線請求,建立一條資料鏈 路來傳送資料。