您的位置:首页 > 科技 > IT业 > SpringBoot 搭建sftp服务 实现远程上传和下载文件

SpringBoot 搭建sftp服务 实现远程上传和下载文件

2024/9/9 6:00:59 来源:https://blog.csdn.net/Komatsu_1137/article/details/139843674  浏览:    关键词:SpringBoot 搭建sftp服务 实现远程上传和下载文件

maven依赖:

<dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.55</version>
</dependency>

application.yml

sftp:protocol: sftphost: port: 22username: rootpassword: spring:servlet:multipart:max-file-size: 500MBmax-request-size: 500MB

注:springboot自带的tomcat会限制上传文件的大小,需要在yml文件里手动设置max-file-size

SftpProperties.java

@Data
@Component
@ConfigurationProperties(prefix = "sftp")
public class SftpProperties {private String host;private int port;private String username;private String password;private String protocol;
}

SftpUtils.java

@Slf4j
@Component
public class SftpUtils {@Resourceprivate SftpProperties sftpProperties;public ChannelSftp createSftp() throws JSchException {JSch jsch = new JSch();log.info("Try to connect sftp[" + sftpProperties.getUsername() + "@" + sftpProperties.getHost() + "]");Session session = createSession(jsch, sftpProperties.getHost(), sftpProperties.getUsername(), sftpProperties.getPort());session.setPassword(sftpProperties.getPassword());session.setConfig("StrictHostKeyChecking", "no");session.connect();log.info("Session connected to {}.", sftpProperties.getHost());Channel channel = session.openChannel(sftpProperties.getProtocol());channel.connect();log.info("Channel created to {}.", sftpProperties.getHost());return (ChannelSftp) channel;}public Session createSession(JSch jsch, String host, String username, Integer port) throws JSchException {Session session = null;if (port <= 0) {session = jsch.getSession(username, host);} else {session = jsch.getSession(username, host, port);}if (session == null) {throw new RuntimeException(host + "session is null");}return session;}public void disconnect(ChannelSftp sftp) {try {if (sftp != null) {if (sftp.isConnected()) {sftp.disconnect();} else if (sftp.isClosed()) {log.error("sftp 连接已关闭");}if (sftp.getSession() != null) {sftp.getSession().disconnect();}}} catch (JSchException e) {log.error("sftp 断开连接失败,原因:{}", e.getMessage(), e);}}
}

SftpController.java

@RestController
public class SftpController {@Autowiredprivate SftpService sftpService;@PostMapping("/upload")public void upload(String remotePath, MultipartFile file) {sftpService.upload(remotePath, file);}@GetMapping("/download")public void download(String remotePath, String localPath) {sftpService.download(remotePath, localPath);}
}

SftpServiceImpl.java

@Service
@Slf4j
public class SftpServiceImpl implements SftpService {@Autowiredprivate SftpUtils sftpUtils;@Overridepublic void upload(String remotePath, MultipartFile file) {ChannelSftp sftp = null;try {// 开启sftp连接sftp = sftpUtils.createSftp();sftp.cd(remotePath);log.info("修改目录为:{}", remotePath);// 上传文件sftp.put(file.getInputStream(), file.getOriginalFilename());log.info("上传文件成功,目标目录:{}", remotePath);} catch (Exception e) {log.error("上传文件失败,原因:{}", e.getMessage(), e);throw new RuntimeException("上传文件失败");} finally {// 关闭sftpsftpUtils.disconnect(sftp);}}@Overridepublic void download(String remotePath, String localPath) {ChannelSftp sftp = null;OutputStream outputStream = null;try {sftp = sftpUtils.createSftp();String path = remotePath.substring(0, remotePath.lastIndexOf("/"));String fileName = remotePath.substring(remotePath.lastIndexOf("/") + 1);System.out.println("path:" + path);System.out.println("fileName:" + fileName);sftp.cd(path);if(isFileExist(remotePath, sftp)) { //如果远程文件存在File localFile = new File(localPath);if(!localFile.exists()) { //如果本地目录不存在,则创建目录localFile.mkdirs();}outputStream = new FileOutputStream(new File(localPath + "/" + fileName));sftp.get(fileName, outputStream);log.info("下载文件成功");} else {log.error("远程文件不存在");throw new RuntimeException("远程文件不存在");}} catch (Exception e) {log.error("sftp文件下载失败,目标文件名:{},原因:{}", remotePath, e.getMessage(), e);throw new RuntimeException("远程文件下载失败");} finally {// 关闭sftpsftpUtils.disconnect(sftp);}}//判断文件是否存在private boolean isFileExist(String remotePath, ChannelSftp sftp) {try {SftpATTRS lstat = sftp.lstat(remotePath);return lstat != null;} catch (Exception e) {log.error("判断文件是否存在失败,原因:{}", e.getMessage(), e);return false;}}
}

接口测试:

上传接口:
请添加图片描述
下载接口:
请添加图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com