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.mzph.cn/diannao/32274.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

人工智能未来的发展趋势如何?

人工智能是当今科技发展的前沿领域&#xff0c;其未来的发展趋势值得关注。随着技术的不断进步和应用的深入&#xff0c;人工智能有望在多个方面取得突破性进展。具体如下&#xff1a; 迈向通用人工智能 技术发展&#xff1a;通用人工智能是指具备多领域智能能力的系统&#x…

java中的日志

springboot自带slf4j框架和logback&#xff0c;我们可以移除spring的logging&#xff0c;然后再带入自己的日志框架。 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusio…

Docker 安装运行命令解读安装Mysql

MySQL 8.0 镜像 docker pull mysql:8.0运行命令 dockerrun --namemysql-container -e MYSQL_ROOT_PASSWORD123456 -p 3306:3306-d mysql:8.0docker run 创建并运行容器 -p 在后台运行 –name mysql 给当前容器取名叫mysql -p 3306:3306 端口映射&#xff0c;容器与主机的…

【MMSegmentation 环境配置】

MMSegmentation 环境配置 1. 创建python 环境2. 安装pytorch3. 安装MMCV4. 安装 MMSegmentation.5. 测试是否安装成功 1. 创建python 环境 conda create --name openmmlab python3.8 -y conda activate openmmlab2. 安装pytorch On GPU platforms: conda install pytorch tor…

如何混淆 net core 8 架构 C# 编译程序

如何混淆 net core 8 架构 C# 编译程序 一、使用混淆工具 .NET Reactor V6.9二、net core 8 架构 C# 编译程序&#xff08;发布的单文件&#xff09;1、通过发布的单文件程序&#xff0c;可以直接在 .NET Reactor 拖入或打开 &#xff0c;勾选自己需要的保护功能。2、勾选自己需…

Oracle day9

------------------------------------------------------------------------------------ --创建用户 create user test1 identified by 123456; create user ZJun identified by 888888; --授予权限 grant create session to test1; grant create session to ZJun; --删除用…

迈向百亿亿次人工智能数据基础设施

对我来说&#xff0c;在MinIO已经一个多星期了。沉浸在白板会议、架构审查和客户电话中的最大收获是&#xff0c;产品的简单性既是其显着特征&#xff0c;也是其最具决定性的价值驱动因素之一。在规模上尤其如此。由于人工智能的进步&#xff0c;计算能力的爆炸性增长对数据格局…

ArkUI 开发学习随记——登陆界面,正圆头像,主页顶部,列表项案例源码

目录 案例一&#xff1a;登录界面 案例二&#xff1a;正圆头像&#xff0c;胶囊按钮 案例三&#xff1a;主页顶部 案例四&#xff1a;列表项 案例一&#xff1a;登录界面 代码&#xff1a; build() {Column({space:10}){Image($r("app.media.naxida")).width(100)…

什么是N卡和A卡?有什么区别?

名人说&#xff1a;莫听穿林打叶声&#xff0c;何妨吟啸且徐行。—— 苏轼《定风波莫听穿林打叶声》 本篇笔记整理&#xff1a;Code_流苏(CSDN)&#xff08;一个喜欢古诗词和编程的Coder&#x1f60a;&#xff09; 目录 一、什么是N卡和A卡&#xff1f;有什么区别&#xff1f;…

福州大学 2022~2023 学年第 1 学期考试 A 卷压轴题参考答案

题目&#xff1a; 定义一个抽象类Structure&#xff08;含有纯虚函数type函数&#xff0c;用以显示当前结构的类型&#xff1b; 含有show函数&#xff09;&#xff0c; 在此基础上派生出Building类, 用来存储一座楼房的层数、房间数以及它的总平方米数。 建立派生 类House&am…

[Django学习]查询过滤器(lookup types)

1.exact exact用于精确匹配字段的值。适用于需要精确查找某个字段值的场景。 Book.objects.filter(title__exactHarry Potter) 上面的查询会查找标题完全为“Harry Potter”的书籍。 2.iexact iexact忽略大小写地精确匹配字段的值。适用于需要忽略大小写进行精确匹配的场…

已解决java.security.acl.AclNotFoundException异常的正确解决方法,亲测有效!!!

已解决java.security.acl.AclNotFoundException异常的正确解决方法&#xff0c;亲测有效&#xff01;&#xff01;&#xff01; 目录 问题分析 出现问题的场景 报错原因 解决思路 解决方法 分析错误日志 检查ACL文件路径和名称 确认系统权限 修改代码逻辑 确保ACL文…

安卓浏览器区分启动、打开、分享

搞了几个钟头&#xff0c;终于全兼容了&#xff0c;分享有2种类型&#xff01; void getDataFromIntent(Intent intent) {if (intent.getAction().equals(Intent.ACTION_VIEW)) {urln intent.getDataString();if (urln ! null) {if (urln.contains("\n"))urln url…

数据分析方法之对比思维

数据分析方法论 对比分析是将两个或两个以上具有可比性的数据进行比较&#xff0c;分析其中的差异&#xff0c;以揭示事物的发展规律。 数据分析之对比思维 归纳方法——穆勒五法&#xff1a;分别是求同法、求异法、共用法、共变法、剩余法。求同法&#xff1a;比相同 2.1求…

利用 Python 和 AI 技术制作智能问答机器人

利用 Python 和 AI 技术制作智能问答机器人 引言 在人工智能的浪潮下&#xff0c;智能问答机器人成为了一种非常实用的技术。它们能够处理大量的查询&#xff0c;提供即时的反馈&#xff0c;并且可以通过机器学习技术不断优化自身的性能。本文将介绍如何使用 Python 来开发一…

现在这个行情,又又又要开始准备面试了~~

亲爱的程序员朋友们: 这些资料曾经帮助过许多有志之士顺利拿下抖音、快手、阿里等大厂的Offer&#xff0c;现在也希望它们能为你的面试旅程助力&#xff01; 关注【程序员世杰】回复【1024】惊喜等你来拿&#xff01; 截图 关注【程序员世杰】回复【1024】惊喜等你来拿&#xf…

python入门基础知识(错误和异常)

本文部分内容来自菜鸟教程Python 基础教程 | 菜鸟教程 (runoob.com) 本人负责概括总结代码实现。 以此达到快速复习目的 目录 语法错误 异常 异常处理 try/except try/except...else try-finally 语句 抛出异常 用户自定义异常 内置异常类型 常见的标准异常类型 语法…

数据结构---二叉树前中后序遍历

1. 某完全二叉树按层次输出&#xff08;同一层从左到右&#xff09;的序列为 ABCDEFGH 。该完全二叉树的前序序列为() A: ABDHECFG B: ABCDEFGH C: HDBEAFCG D: HDEBFGCA 2. 二叉树的先序遍历和中序遍历如下&#xff1a;先序遍历: EFHIGJK; 中序遍历: HFIEJKG. 则二叉…

exe4j使用笔记(jar包转exe工具)

文章目录 配置项1. Welcome2. Project type3. Application info4. Executable info5. Java invocation6. JRE7. Splash screen8. Messages9. Compile executable10. Finished 其他下载地址(官网地址??) 配置项 总共10个配置项。 1. Welcome 略(不用填) 2. Project type …

Unit redis-server.service could not be found.

我的报错如下Unit redis-server.service could not be found. 关键是刷新后台服务 sudo systemctl daemon-reload启动redis-server sudo systemctl start redis-server查看redis-Server服务状态 sudo systemctl status redis-server