因为主要是记录上传文件,下载文件的方法以后再说.
创建链接
下面展示一些 内联代码片
。
创建链接
// 链接
public static FTPClient ftpClient=null;
public static void initConn(){
if(ftpClient==null||!ftpClient.isAvailable()){
String hostname = xxxx;
int port =Integer.valueOf(xxxx);
String username = xxxx;
String password = xxxx;
ftpClient = new FTPClient();
ftpClient.setControlEncoding("UTF-8");
//创建
try {
//连接FTP服务器
ftpClient.connect(hostname, port);
//登录FTP服务器
ftpClient.login(username, password);
//是否成功登录FTP服务器
int replyCode = ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(replyCode)){
System.out.println("ftp链接失败");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
上传文件
下面展示一些 内联代码片
。
上传文件
/**
* 上传文件(可供Action/Controller层使用)
* @param hostname FTP服务器地址
* @param port FTP服务器端口号
* @param username FTP登录帐号
* @param password FTP登录密码
* @param pathname FTP服务器保存目录
* @param fileName 上传到FTP服务器后的文件名称
* @param is 输入文件流
* @return
*/
public static boolean uploadFile(String pathname, String fileName, InputStream is){
boolean flag = false;
try {
initConn();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//保证可以创建多层目录
if (!ftpClient.changeWorkingDirectory(pathname)) {
//如果目录不存在创建目录
String[] dirs = pathname.split("/");
String tempPath = "";
for (String dir : dirs) {
if (null == dir || "".equals(dir)) continue;
tempPath += "/" + dir;
if (!ftpClient.changeWorkingDirectory(tempPath)) {
if (!ftpClient.makeDirectory(tempPath)) {
System.out.println("创建目录失败");
return false;
} else {
ftpClient.changeWorkingDirectory(tempPath);
}
}
}
}
ftpClient.storeFile(fileName, is);
is.close();
ftpClient.logout();
flag = true;
} catch (Exception e) {
//e.printStackTrace();
//次数
if (++vcount <= VMAX) {
System.out.println("保存附件失败",e);
System.out.println("第["+ vcount +"]次重新保存文件到ftp................");
return uploadFile(pathname, fileName, is);
} else{
System.out.println("重复保存附件"+VMAX+"次失败,跳过本次保存",e);
}
} finally{
if(is!=null){
try {
is.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
return flag;
}