准备username,password,ip 及端口
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
SftpModel model = new SftpModel();
model.setSession(session);
model.setSftp(sftp);
注意先把网络安全策略开通。
接下来上传图片
boolean ret = false;
try {
// sftp.cd(basePath);
sftp.cd(ftpPath);
ret = true;
} catch (SftpException e) {
// 目录不存在,则创建文件夹
String[] dirs = ftpPath.split("/");
String tempPath = "";
for (String dir : dirs) {
if (null == dir || "".equals(dir))
continue;
tempPath+="/"+dir;
//tempPath = dir;
try {
sftp.cd(tempPath);
ret = true;
} catch (SftpException ex) {
try {
sftp.mkdir(tempPath);
sftp.cd(tempPath);
ret = true;
} catch (SftpException e1) {
ret = false;
return ret;
} catch (Exception e1) {
ret = false;
return ret;
}
} catch (Exception e1) {
ret = false;
return ret;
}
}
ret = true;
} catch (Exception e1) {
ret = false;
return ret;
}
try {
sftp.put(input, sftpFileName);// 上传文件
ret = true;
} catch (SftpException e) {
ret = false;
}
没文件夹建文件夹,有就上传