zip上传文件服务器
//往文件服务器上传
//todayDate当前为自定义,也可修改为当前日期格式
String todayDate = (new SimpleDateFormat("yyyyMMdd HHmmss")).format(calendar.getTime());
//在数据库里配置file_server_url、file_server_port等相关参数,查询系统值(系统后台参数key),返回系统后台参数集合
String url = paramService.selectGetPapamValue("file_server_url").getParamValue();
String port = paramService.selectGetPapamValue("file_server_port").getParamValue();
String userName = paramService.selectGetPapamValue("file_server_userName").getParamValue();
String pwd = paramService.selectGetPapamValue("file_server_password").getParamValue();
//连接服务器
SFTPUtils.getConnect(url,port,userName,pwd);
//文件上传服务器
SFTPUtils.uploadFile(自定义服务器路径 + todayDate + ".zip", 自定义服务器路径 , todayDate + ".zip");
//关闭服务器
SFTPUtils.close();
/**
* 连接服务器
* @param host
* @param port
* @param userName
* @param password
* @return
* @throws Exception
*/
public static ChannelSftp getConnect(String host, String port, String userName, String password)
throws Exception {
try {
JSch jsch = new JSch();
// 获取sshSession
sshSession = jsch.getSession(userName, host, Integer.parseInt(port));
// 添加s密码
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
// 开启sshSession链接
sshSession.connect();
// 获取sftp通道
ftpClient = (ChannelSftp) sshSession.openChannel("sftp");
// 开启
ftpClient.connect();
loggerMonitor.debug("success ..........");
} catch (Exception e) {
e.printStackTrace();
throw new Exception("连接sftp服务器异常。。。。。。。。");
}
return ftpClient;
}
/**
* 上传
* @param upload_path 上传文件路径
* @param ftp_path 服务器保存路径
* @param newFileName 新文件名
* @throws Exception
*/
public static void uploadFile(String upload_path, String ftp_path, String newFileName) throws Exception {
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(upload_path));
// if (!isExistDir(BaseConstants.DEFAULT_BASEDIR, ftpClient)) {
// ftpClient.mkdir("/data");
// ftpClient.mkdir(BaseConstants.DEFAULT_BASEDIR);
// }
if(!isExistDir(ftp_path, ftpClient)) {
ftpClient.mkdir(ftp_path);
}
ftpClient.cd(ftp_path);
ftpClient.put(fis, newFileName);
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Upload file error.");
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
throw new Exception("close stream error.");
}
}
}
}
/**
* 关闭
*
* @throws Exception
*/
public static void close() throws Exception {
loggerMonitor.debug("close............");
try {
ftpClient.disconnect();
sshSession.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception("close stream error.");
}
}