直接上代碼
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);
}
這個類也提供了其他方法,可以直接用