一、添加依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
二、ftp的配置参数封装
@Data
@Component
public class SftpConfigProperties {
private String ip;
private Integer port;
private String username;
private String password;
private String userHouseApplyPath;
}
三、获取sftp连接
public ChannelSftp connect(SftpConfigProperties sftpConfigProperties) {
ChannelSftp sftp = null;
JSch jsch = new JSch();
try {
Session session = jsch.getSession(sftpConfigProperties.getUsername(), sftpConfigProperties.getIp(), sftpConfigProperties.getPort());
session.setPassword(sftpConfigProperties.getPassword());
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
session.connect();
log.info("sftp session连接成功");
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
log.info("sftp登录成功");
} catch (JSchException e) {
log.error("sftp链接失败", e);
}
return sftp;
}
四、上传图片到sftp服务器
public void uploadFile(String remotePath, String filePath, ChannelSftp sftp) {
URL urlFile;
InputStream inStream;
try {
urlFile = new URL(remotePath);
inStream = urlFile.openStream();
sftp.cd(filePath);
sftp.put(inStream, getFileName(remotePath), ChannelSftp.OVERWRITE);
} catch (IOException | SftpException e) {
log.error("上传图片到ftp服务器失败", e);
} finally {
try {
disconnect(sftp);
} catch (JSchException e) {
log.error("关闭sftp链接异常", e);
}
}
}
public String getFileName(String fileName) {
fileName = fileName.replaceAll("\\\\", "/");
int index = fileName.lastIndexOf("/");
return index == -1 ? fileName : fileName.substring(index + 1);
}
五、下载文件
public void download(String directory, String downloadFile, String saveFile) {
try {
if (sftp == null || sftp.getSession() != null || sftp.getSession().isConnected()) {
connect();
}
} catch (JSchException e) {
log.error("sftp服务器连接失败", e);
}
try (FileOutputStream out = new FileOutputStream(saveFile)) {
sftp.cd(directory);
sftp.get(downloadFile, out);
} catch (Exception e) {
log.error("下载文件失败");
} finally {
try {
disconnect();
} catch (JSchException e) {
log.error("关闭sftp链接异常", e);
}
}
}
六、关闭sftp连接
public void disconnect(ChannelSftp sftp) throws JSchException {
if (sftp != null) {
if (sftp.getSession().isConnected()) {
sftp.getSession().disconnect();
}
if (sftp.isConnected()) {
sftp.disconnect();
}
}
}