1.关于FTP
FTP:File Transfer Protocol,文件传输协议,是TCP/IP网络上两台计算机传送文件的协议,是在TCP/IP网络和INTERNET上最早使用的协议之一,它属于网络协议组的应用层。
1)主要功能
提供文件的共享(计算机程序 / 数据); 支持间接使用远程计算机; 使用户不因各类主机文件存储器系统的差异而受影响; 可靠且有效的传输数据。
2)用户授权
在ftp的使用过程中,必须首先登录,在远程主机上获得相应的权限以后,方可上传或下载文件。也就是说,要想同哪一台计算机传送文件,就必须具有哪一台计算机的适当授权。换言之,除非有用户ID和口令,否则便无法传送文件。这种情况违背了Internet的开放性,Internet上的FTP主机何止千万,不可能要求每个用户在每一台主机上都拥有帐号。因此就衍生出了匿名服务,在这种设置下,用户不需要帐号就可以登录服务器,默认情况下,匿名用户的用户名是:“anonymous”。这个帐号不需要密码,虽然通常要求输入用户的邮件地址作为认证密码,但这只是一些细节或者此邮件地址根本不被确定,而是依赖于FTP服务器的配置情况。
3)使用模式
FTP有两种使用模式:主动和被动。主动模式要求客户端和服务器端同时打开并且监听一个端口以建立连接。在这种情况下,客户端由于安装了防火墙会产生一些问题。所以,创立了被动模式。被动模式只要求服务器端产生一个监听相应端口的进程,这样就可以绕过客户端安装了防火墙的问题。[4]一个主动模式的FTP连接建立要遵循以下步骤:
1.客户端打开一个随机的端口(端口号大于1024,在这里,我们称它为x),同时一个FTP进程连接至服务器的21号命令端口。此时,源端口为随机端口x,在客户端,远程端口为21,在服务器。
2.客户端开始监听端口(x+1),同时向服务器发送一个端口命令(通过服务器的21号命令端口),此命令告诉服务器客户端正在监听的端口号并且已准备好从此端口接收数据。这个端口就是我们所知的数据端口。
3.服务器打开20号源端口并且建立和客户端数据端口的连接。此时,源端口为20,远程数据端口为(x+1)。
4.客户端通过本地的数据端口建立一个和服务器20号端口的连接,然后向服务器发送一个应答,告诉服务器它已经建立好了一个连接。
被动模式FTP:
为了解决服务器发起到客户的连接的问题,人们开发了一种不同的FTP连接方式。这就是所谓的被动方式,或者叫做PASV,当客户端通知服务器它处于被动模式时才启用。
在被动方式FTP中,命令连接和数据连接都由客户端发起,这样就可以解决从服务器到客户端的数据端口的入方向连接被防火墙过滤掉的问题。
当开启一个 FTP连接时,客户端打开两个任意的非特权本地端口(N > 1024和N+1)。第一个端口连接服务器的21端口,但与主动方式的FTP不同,客户端不会提交PORT命令并允许服务器来回连它的数据端口,而是提交 PASV命令。这样做的结果是服务器会开启一个任意的非特权端口(P > 1024),并发送PORT P命令给客户端。然后客户端发起从本地端口N+1到服务器的端口P的连接用来传送数据。
对于服务器端的防火墙来说,必须允许下面的通讯才能支持被动方式的FTP:
1. 从任何大于1024的端口到服务器的21端口 (客户端的初始化连接)
2.服务器的21端口到任何大于1024的端口 (服务器响应到客户端的控制端口的连接)
3. 从任何大于1024端口到服务器的大于1024端口 (客户端初始化数据连接到服务器指定的任意端口)
4.服务器的大于1024端口到远程的大于1024的端口(服务器发送ACK响应和数据到客户端的数据端口)
4)文件传输格式
FTP可用多种格式传输文件,通常由系统决定,大多数系统(包括UNIX系统)只有两种模式:文本模式和二进制模式。文本传输器使用ASCII字符,并由回车键和换行符分开,而二进制不用转换或格式化就可传字符,二进制模式比文本模式更快,并且可以传输所有ASCII值,所以系统管理员一般将FTP设置成二进制模式。
ASCII 模式和BINARY模式的区别是回车换行的处理,binary模式不对数据进行任何处理,asci模式将回车换行转换为本机的回车字符。
一般来说,我们最好都用binary方式,这样可以保证不出错。如果有文本格式转换的问题,即unix格式的文本和dos格式的文本之间的转换,有很多工具可以做的,不要在ftp传输的时候冒险,尤其是你如果对这些东西不是非常清楚的话。
2.JAVA实现FTP
目前,已经有很多公开免费的ftp客户端类库,如simpleftp,J-ftp,jakarta的commons-net等,还有很多其他的ftpclient,本文将使用jakarta的commons-net实现FTP服务器上文件的上传和下载。
3.实例
/**
*
*/
package com.siyuan.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
/**
*
*/
public class FTPClientUtil {
public static final Log log = LogFactory.getLog(FTPClientUtil.class);
//FTP server configuration--IP key,value is type of String
public static final String SERVER_IP = "SERVER_IP";
//FTP server configuration--Port key,value is type of Integer
public static final String SERVER_PORT = "SERVER_PORT";
//FTP server configuration--ANONYMOUS Log in key, value is type of Boolean
public static final String IS_ANONYMOUS = "IS_ANONYMOUS";
//user name of anonymous log in
public static final String ANONYMOUS_USER_NAME = "anonymous";
//password of anonymous log in
public static final String ANONYMOUS_PASSWORD = "";
//FTP server configuration--log in user name, value is type of String
public static final String USER_NAME = "USER_NAME";
//FTP server configuration--log in password, value is type of String
public static final String PASSWORD = "PASSWORD";
//FTP server configuration--PASV key, value is type of Boolean
public static final String IS_PASV = "IS_PASV";
//FTP server configuration--working directory key, value is type of String
// While logging in, the current directory is the user's home directory,
// the workingDirectory must be set based on it.
// Besides, the workingDirectory must exist, it can not be created automatically.
// If not exist, file will be uploaded in the user's home directory.
// If not assigned, "/" is used.
public static final String WORKING_DIRECTORY = "WORKING_DIRECTORY";
/**
* Upload a file to FTP server.
* @param serverCfg : FTP server configuration
* @param filePathToUpload : path of the file to upload
* @param fileStoredName : the name to give the remote stored file,
* null, "" and other blank word will be replaced by the file name to upload
* @throws IOException
* @throws SocketException
*/
public static final void upload(Map<String, Object> serverCfg,
String filePathToUpload, String fileStoredName)
throws SocketException, IOException {
upload(serverCfg, new File(filePathToUpload), fileStoredName);
}
/**
* Upload a file to FTP server.
* @param serverCfg : FTP server configuration
* @param fileToUpload : file to upload
* @param fileStoredName : the name to give the remote stored file,
* null, "" and other blank word will be replaced by the file name to upload
* @throws IOException
* @throws SocketException
*/
public static final void upload(Map<String, Object> serverCfg,
File fileToUpload, String fileStoredName) throws SocketException,
IOException {
if (!fileToUpload.exists()) {
throw new IllegalArgumentException("File to upload does not exists:" + fileToUpload.getAbsolutePath());
}
if (!fileToUpload.isFile()) {
throw new IllegalArgumentException("File to upload is not a file:" + fileToUpload.getAbsolutePath());
}
if (StringUtils.isBlank((String) serverCfg.get(SERVER_IP))) {
throw new IllegalArgumentException("SERVER_IP must be contained in the FTP server configuration.");
}
transferFile(true, serverCfg, fileToUpload, fileStoredName, null, null);
}
/**
* Download a file from FTP server
* @param serverCfg : FTP server configuration
* @param fileNameToDownload : file name to be downloaded
* @param fileStoredPath : stored path of the downloaded file in local
* @throws SocketException
* @throws IOException
*/
public static final void download(Map<String, Object> serverCfg,
String fileNameToDownload, String fileStoredPath)
throws SocketException, IOException {
if (StringUtils.isBlank(fileNameToDownload)) {
throw new IllegalArgumentException("File name to be downloaded can not be blank.");
}
if (StringUtils.isBlank(fileStoredPath)) {
throw new IllegalArgumentException("Stored path of the downloaded file in local can not be blank.");
}
if (StringUtils.isBlank((String) serverCfg.get(SERVER_IP))) {
throw new IllegalArgumentException("SERVER_IP must be contained in the FTP server configuration.");
}
transferFile(false, serverCfg, null, null, fileNameToDownload, fileStoredPath);
}
private static final void transferFile(boolean isUpload, Map<String, Object> serverCfg,
File fileToUpload, String serverFileStoredName,
String fileNameToDownload, String localFileStoredPath)
throws SocketException, IOException {
String host = (String) serverCfg.get(SERVER_IP);
Integer port = (Integer) serverCfg.get(SERVER_PORT);
Boolean isAnonymous = (Boolean) serverCfg.get(IS_ANONYMOUS);
String username = (String) serverCfg.get(USER_NAME);
String password = (String) serverCfg.get(PASSWORD);
Boolean isPASV = (Boolean) serverCfg.get(IS_PASV);
String workingDirectory = (String) serverCfg.get(WORKING_DIRECTORY);
FTPClient ftpClient = new FTPClient();
InputStream fileIn = null;
OutputStream fileOut = null;
try {
if (port == null) {
log.debug("Connect to FTP server on " + host + ":" + FTP.DEFAULT_PORT);
ftpClient.connect(host);
} else {
log.debug("Connect to FTP server on " + host + ":" + port);
ftpClient.connect(host, port);
}
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
log.error("FTP server refuses connection");
return;
}
if (isAnonymous != null && isAnonymous) {
username = ANONYMOUS_USER_NAME;
password = ANONYMOUS_PASSWORD;
}
log.debug("Log in FTP server with username = " + username + ", password = " + password);
if (!ftpClient.login(username, password)) {
log.error("Fail to log in FTP server with username = " + username + ", password = " + password);
ftpClient.logout();
return;
}
// Here we will use the BINARY mode as the transfer file type,
// ASCII mode is not supportted.
log.debug("Set type of the file, which is to upload, to BINARY.");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
if (isPASV != null && isPASV) {
log.debug("Use the PASV mode to transfer file.");
ftpClient.enterLocalPassiveMode();
} else {
log.debug("Use the ACTIVE mode to transfer file.");
ftpClient.enterLocalActiveMode();
}
if (StringUtils.isBlank(workingDirectory)) {
workingDirectory = "/";
}
log.debug("Change current working directory to " + workingDirectory);
ftpClient.changeWorkingDirectory(workingDirectory);
if (isUpload) { //upload
if (StringUtils.isBlank(serverFileStoredName)) {
serverFileStoredName = fileToUpload.getName();
}
fileIn = new FileInputStream(fileToUpload);
log.debug("Upload file : " + fileToUpload.getAbsolutePath() + " to FTP server with name : " + serverFileStoredName);
if (!ftpClient.storeFile(serverFileStoredName, fileIn)) {
log.error("Fail to upload file, " + ftpClient.getReplyString());
} else {
log.debug("Success to upload file.");
}
} else { //download
// make sure the file directory exists
File fileStored = new File(localFileStoredPath);
if (!fileStored.getParentFile().exists()) {
fileStored.getParentFile().mkdirs();
}
fileOut = new FileOutputStream(fileStored);
log.debug("Download file : " + fileNameToDownload + " from FTP server to local : " + localFileStoredPath);
if (!ftpClient.retrieveFile(fileNameToDownload, fileOut)) {
log.error("Fail to download file, " + ftpClient.getReplyString());
} else {
log.debug("Success to download file.");
}
}
ftpClient.noop();
ftpClient.logout();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException f) {
}
}
if (fileIn != null) {
try {
fileIn.close();
} catch (IOException e) {
}
}
if (fileOut != null) {
try {
fileOut.close();
} catch (IOException e) {
}
}
}
}
}
4.参考资料
http://baike.baidu.com/view/103832.htm?fromId=369