直接上代码
/**
* 通过ftp上传zip
* @param filePath
*/
private static boolean ftpUploadZip(String filePath,String fileName){
boolean ftpResult = false;
File file = new File(filePath);
if (!file.exists()) {
logger.info(“没有获取到本地文件,请检查!”);
return false;
} else {
//创建连接
ChannelSftp sftp = SftpUploadUtil.getFTPClient();
if(null != sftp) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(filePath));
ftpResult = true;
sftp.put(inputStream,fileName);
inputStream.close();
logger.error(“ftp上传完毕,成功”);
} catch (Exception e) {
logger.error(“ftp上传附件失败”);
e.printStackTrace();
} finally {
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return ftpResult;
}
}
SftpUploadUtil类
package com.vtion.finance.web.util.sftp;
import com.commonlib.util.PropertiesUtil;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
public class SftpUploadUtil {
private static final Logger logger = LoggerFactory.getLogger(SftpUploadUtil.class);
//ftp服务器地址
public static String ftpHostname = PropertiesUtil.readValue("file.ftp.url");
//ftp服务器端口号默认为21
public static Integer ftpPort = 22 ;
//ftp登录账号
public static String ftpUsername = PropertiesUtil.readValue("file.ftp.user");
//ftp登录密码
public static String ftpPassword = PropertiesUtil.readValue("file.ftp.password");
public static ChannelSftp getFTPClient(){
//实现FTP核心类
ChannelSftp sftp = null;
//session会话对象
Session ftpsession = null;
Channel ftpchannel = null;
JSch jSch = new JSch();
try {
jSch.getSession(ftpUsername,ftpHostname,ftpPort);
ftpsession = jSch.getSession(ftpUsername,ftpHostname,ftpPort);
ftpsession.setPassword(ftpPassword);
ftpsession.setTimeout(600000);
Properties ftpConfig = new Properties();
ftpConfig.put("StrictHostKeyChecking", "no");
ftpsession.setConfig(ftpConfig);
// 通过Session建立链接
ftpsession.connect();
logger.info("SFTP Session connected.........");
ftpchannel = ftpsession.openChannel("sftp");
// 建立SFTP通道的连接
ftpchannel.connect();
logger.info("SFTP Channel connected.........");
sftp = (ChannelSftp) ftpchannel;
logger.info("Connected to" + ftpHostname);
}catch (Exception e) {
logger.error("initFtpClient:{}",e.getMessage(),e);
}
return sftp;
}
}
测试类。请无视xml这个参数。业务需要才有他
public static void main(String[] args) throws Exception {
String xml = “XXX”
String filePath = “E:/athena_conf/Athena/onlineTrade/20171231/78E0000251/zip/image.zip” ;
String riskCode = “213123”;
String prtNo = “9900073781”;
String s = imageCallService(filePath, xml, prtNo);
System.out.println(s);
}
这个类也提供了其他方法,可以直接用