在过去的几年工作中,曾经多次需要把文件上传到单独的服务器,而程序是在单独的服务器上部署的,在进行文件操作的时候就需要跨服务器进行操作包括:文件上传、文件下载、文件删除等。跨服务器文件操作一般是需要FTP协议和SFTP协议两种,现在就通过Java实现FTP协议的文件上传。要实现FTP操作文件需要引入jar包: commons-net-1.4.1.jar
具体代码如下:
import java.io.*;
import java.net.MalformedURLException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* ftp 文件上传工具类
* 所需jar包(commons-net-1.4.1.jar)
*/
public class FtpUtils {
//ftp服务器地址
public String hostname ;
//ftp服务器端口号默认为21
public Integer port ;
//ftp登录账号
public String username ;
//ftp登录密码
public String password ;
//FTP客户端对象
public FTPClient ftpClient = null;
//构造方法
public FtpUtils(String hostname,Integer port,String username,String password){
this.hostname = hostname;
this.port = port;
this.username = username;
this.password = password;
}
/**
* 初始化ftp服务器
*/
public void initFtpClient() {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("utf-8");
try {
System.out.println("connecting...ftp服务器:"+this.hostname+":"+this.port);
ftpClient.connect(hostname, port); //连接ftp服务器
ftpClient.login(username, password); //登录ftp服务器
int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
if(!FTPReply.isPositiveCompletion(replyCode)){
System.out.println("connect failed...ftp服务器:"+this.hostname+":"+this.port);
}
System.out.println("connect successfu...ftp服务器:"+this.hostname+":"+this.port);
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* 上传文件
* @param pathname ftp服务保存地址
* @param fileName 上传到ftp的文件名
* @param originfilename 待上传文件的名称(绝对地址) *
* @return
*/
public boolean uploadFile( String pathname, String fileName,String originfilename){
boolean flag = false;
InputStream inputStream = null;
try{
System.out.println("开始上传文件");
inputStream = new FileInputStream(new File(originfilename));
initFtpClient();
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
CreateDirecroty(pathname);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.enterLocalPassiveMode();
flag =ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
System.out.println("上传文件成功");
}catch (Exception e) {
System.out.println("上传文件失败");
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();