当前位置: 首页 > news >正文

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;}}
}

接口测试:

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

http://www.lryc.cn/news/383636.html

相关文章:

  • IDEA中使用leetcode 刷题
  • 华为海思CPU解读
  • 中介子方程三十三
  • 今年哪两个行业可能有贝塔?
  • 嵌入式软件开发工具使用介绍
  • 【TB作品】MSP430G2553,单片机,口袋板, 交通灯控制系统
  • windows 安装 Kubernetes(k8s)
  • C语言 | Leetcode C语言题解之第189题轮转数组
  • 【安全审核】音视频审核开通以及计费相关
  • 【实战】Spring Cloud Stream 3.1+整合Kafka
  • java之可变字符串之append方法
  • [保姆级教程]uniapp自定义导航栏
  • 项目训练营第二天
  • 考研数学一有多难?130+背后的残酷真相
  • vue2脚手架笔记总结1
  • 校园巡礼:一周只上四天课,入学即发钱?深圳理工大学,开局即王炸
  • 免交互 实验
  • Sublime Text 设置
  • spire.Pdf 将pdf转成image
  • 仓颉编程语言 -- 初识(一)
  • 前端JS必用工具【js-tool-big-box】学习,数值型数组的正向排序和倒向排序
  • python web框架哪家强?Flask、Django、FastAPI对比
  • Mybatis plus:IService接口
  • 时序分析基本概念介绍——min pulse width 最小脉冲宽度
  • PHP原生代码生成pdf---解决中文乱码问题
  • 智慧车库管理系统
  • 每日新闻掌握【2024年6月26日 星期三】
  • InVEST实践及在生态系统服务供需、固碳、城市热岛、论文写作等实际项目中应用
  • 慧科新闻搜索研究数据库的使用指南及个人获取途径
  • SpringBoot学习03-[Spring Boot与Web开发]