import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import com.hikvision.util.Configuration;
public class FTPUtil {
public static String startCollection(String filePath, String fileName,
InputStream input) {
String host = Configuration.GetConfig("ftp_host");
String port = Configuration.GetConfig("ftp_port");
String user = Configuration.GetConfig("ftp_user");
String pwd = Configuration.GetConfig("ftp_pwd");
String basePath = Configuration.GetConfig("ftp_basePath");
return uploadFile(host, Integer.parseInt(port), user, pwd, basePath,
filePath, fileName, input);
}
/**
* 向FTP服务器上传文件
* [@param](https://my.oschina.net/u/2303379) host FTP服务器hostname
* [@param](https://my.oschina.net/u/2303379) port FTP服务器端口
* [@param](https://my.oschina.net/u/2303379) username FTP登录账号
* [@param](https://my.oschina.net/u/2303379) password FTP登录密码
* [@param](https://my.oschina.net/u/2303379) basePath FTP服务器基础目录
* @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回success,否则返回错误信息
*/
public static String uploadFile(String host, int port, String username,
String password, String basePath, String filePath, String filename,
InputStream input) {
String result = null;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, port);
ftp.login(username, password);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
result = "FTP服务器无法连接";
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)) {
result = "FTP创建文件目录【" + tempPath + "】失败";
return result;
} else {
ftp.changeWorkingDirectory(tempPath);
}
}
}
}
//设置上传文件的类型为二进制类型
ftp.setFileType(FTP.BINARY_FILE_TYPE);
//这个方法的意思就是每次数据连接之前,ftp client告诉ftp server开通一个端口来传输数据。
//为什么要这样做呢,因为ftp server可能每次开启不同的端口来传输数据,但是在linux上或者其他服务器上面,由于安全限制,可能某些端口没有开启,所以就出现阻塞。
//本地不加这段代码没问题,放到测试服务器就需要加上,否则文件可能会无法写入
ftp.enterLocalPassiveMode();
//上传文件
if (!ftp.storeFile(filename, input)) {
result = "文件无法写入FTP,请确认服务器是否有权限";
return result;
}
input.close();
ftp.logout();
result = "success";
} catch (IOException e) {
e.printStackTrace();
result = "读取文件失败," + e.getMessage();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
result = e.getMessage();
}
}
}
return result;
}
}
ftp相关配置
ftp_host=ftp.com
ftp_port=400
ftp_user=user
ftp_pwd=password
ftp_basePath=/test/