1、导入jar包
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
2、yaml文件配置参数
ftp:
host: XXXXXX
port: 22
username: root
password: XXXXXX
dst: /mnt/file/
3、封装一个将文件上传Linux服务器和删除的工具类
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
@Data
@Component
@ConfigurationProperties(prefix = "ftp")
public class SFTPUtil {
private String host;
private int port;
private String username;
private String password;
private String dst;
public String uploadFileToLinux(MultipartFile file) {
String fileName = null;
try {
fileName = file.getOriginalFilename();
fileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
String filePath = this.dst + fileName;
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put(file.getInputStream(), filePath);
sftpChannel.disconnect();
session.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return fileName;
}
public void deleteFileToLinux(String fileName) {
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.rm(this.dst + fileName);
sftpChannel.disconnect();
session.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}