java使用Sftp上传图片文件到Linux服务器上
需要依赖
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
<!-- 为了使用@Slf4j注解 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
编写工具类,直接上代码,里面有注释直接就可以用;
@Slf4j
public class uploadUtil {
private static Session session;
private static ChannelSftp channelSftp;
public static ChannelSftp getSFTPClient(String ftpaddress, String ftpPassword,
String ftpUserName,int ftpPort) {
long startTime = System.currentTimeMillis();
JSch jsch = new JSch();
Channel channel = null;
try {
session = jsch.getSession(ftpUserName, ftpaddress,ftpPort);
session.setPassword(ftpPassword);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
long endTime = System.currentTimeMillis();
log.info("连接sftp成功耗时" + (endTime - startTime) + "毫秒");
return (ChannelSftp) channel;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}