java项目使用jsch下载ftp文件

server/2024/10/18 17:20:47/

pom

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

demo1:main方法直接下载

java">package com.example.controller;import com.jcraft.jsch.*;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;public class JSchSFTPFileTransfer {public static void main(String[] args) {String host = "10.*.*.*";//服务器地址String user = "";//用户String password = "";//密码int port = 22;//端口String remoteFilePath = "/home/*/*/ps.xlsx";//拉取文件的路径String localFilePath = "C:\\Users\\*\\Downloads\\ps.xlsx";//下载到本地路径JSch jsch = new JSch();// 初始化对象Session session = null;ChannelSftp sftpChannel = null;InputStream inputStream = null;OutputStream outputStream = null;try {// 创建会话session = jsch.getSession(user, host, port);session.setConfig("StrictHostKeyChecking", "no");session.setPassword(password);session.connect();// 打开 SFTP 通道sftpChannel = (ChannelSftp) session.openChannel("sftp");sftpChannel.connect();//创建本地路径int lastSlashIndex = remoteFilePath.lastIndexOf("/");String path = remoteFilePath.substring(0, lastSlashIndex);File file = new File(path);if (!file.exists()) {try {file.mkdirs();} catch (Exception e) {System.out.println("=====jSchSFTPFileTransfer创建文件夹失败!====");}}// 下载文件inputStream = sftpChannel.get(remoteFilePath);// 上传文件到本地outputStream = new java.io.FileOutputStream(localFilePath);byte[] buffer = new byte[1024];int bytesRead;while ((bytesRead = inputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, bytesRead);}System.out.println("=====jSchSFTPFileTransfer文件下载成功!===="+localFilePath);} catch (JSchException | SftpException | java.io.IOException e) {e.printStackTrace();} finally {// 关闭流、通道和会话if (inputStream != null) {try {inputStream.close();} catch (java.io.IOException e) {e.printStackTrace();}}if (outputStream != null) {try {outputStream.close();} catch (java.io.IOException e) {e.printStackTrace();}}if (sftpChannel != null && sftpChannel.isConnected()) {sftpChannel.disconnect();}if (session != null && session.isConnected()) {session.disconnect();}}}
}

demo2:页面按钮调接口下载

后端
java">package com.example.controller;import com.example.common.utils.SFTPUtil;
import com.jcraft.jsch.SftpException;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class testController {@GetMapping(value = "/export")public ResponseEntity<byte[]> empController(String remotePath) throws Exception {
//        remotePath = "/home/fr/zycpzb/ps.xlsx";String host = "10.1.16.92";int port = 22;String userName = "fr";String password = "Lnbi#0Fr";SFTPUtil sftp = new SFTPUtil(userName, password, host, port);sftp.login();try {byte[] buff = sftp.download(remotePath);HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);headers.setContentDispositionFormData("attachment", "ps.xlsx");return ResponseEntity.ok().headers(headers).body(buff);} catch (SftpException e) {e.printStackTrace();return ResponseEntity.status(500).body(null);}finally {sftp.logout();}}
}

SFTPUtil

java">package com.example.common.utils;import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import com.jcraft.jsch.*;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**** @ClassName: SFTPUtil* @Description: sftp连接工具类* @version 1.0.0*/
public class SFTPUtil {private transient Logger log = LoggerFactory.getLogger(this.getClass());private ChannelSftp sftp;private Session session;/*** FTP 登录用户名*/private String username;/*** FTP 登录密码*/private String password;/*** 私钥*/private String privateKey;/*** FTP 服务器地址IP地址*/private String host;/*** FTP 端口*/private int port;/*** 构造基于密码认证的sftp对象** @param username* @param password* @param host* @param port*/public SFTPUtil(String username, String password, String host, int port) {this.username = username;this.password = password;this.host = host;this.port = port;}/*** 构造基于秘钥认证的sftp对象** @param username* @param host* @param port* @param privateKey*/public SFTPUtil(String username, String host, int port, String privateKey) {this.username = username;this.host = host;this.port = port;this.privateKey = privateKey;}public SFTPUtil() {}/*** 连接sftp服务器** @throws Exception*/public void login() {try {JSch jsch = new JSch();if (privateKey != null) {jsch.addIdentity(privateKey);// 设置私钥log.info("sftp connect,path of private key file:{}", privateKey);}log.info("sftp connect by host:{} username:{}", host, username);session = jsch.getSession(username, host, port);log.info("Session is build");if (password != null) {session.setPassword(password);}Properties config = new Properties();config.put("StrictHostKeyChecking", "no");session.setConfig(config);session.connect();log.info("Session is connected");Channel channel = session.openChannel("sftp");channel.connect();log.info("channel is connected");sftp = (ChannelSftp) channel;log.info(String.format("sftp server host:[%s] port:[%s] is connect successfull", host, port));} catch (JSchException e) {log.error("Cannot connect to specified sftp server : {}:{} \n Exception message is: {}", new Object[]{host, port, e.getMessage()});}}/*** 关闭连接 server*/public void logout() {if (sftp != null) {if (sftp.isConnected()) {sftp.disconnect();log.info("sftp is closed already");}}if (session != null) {if (session.isConnected()) {session.disconnect();log.info("sshSession is closed already");}}}/*** 下载文件** @param directory*            下载目录* @param downloadFile*            下载的文件* @param saveFile*            存在本地的路径* @throws SftpException* @throws FileNotFoundException* @throws Exception*/public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException{if (directory != null && !"".equals(directory)) {sftp.cd(directory);}File file = new File(saveFile);sftp.get(downloadFile, new FileOutputStream(file));log.info("file:{} is download successful" , downloadFile);}/*** 下载文件* @param directory 下载目录* @param downloadFile 下载的文件名* @return 字节数组* @throws SftpException* @throws IOException* @throws Exception*/public byte[] download(String directory, String downloadFile) throws SftpException, IOException{if (directory != null && !"".equals(directory)) {sftp.cd(directory);}InputStream is = sftp.get(downloadFile);byte[] fileData = IOUtils.toByteArray(is);log.info("file:{} is download successful" , downloadFile);return fileData;}/*** 下载文件* @param directory 下载的文件名* @return 字节数组* @throws SftpException* @throws IOException* @throws Exception*/public byte[] download(String directory) throws SftpException, IOException{InputStream is = sftp.get(directory);byte[] fileData = IOUtils.toByteArray(is);log.info("file:{} is download successful" , directory);is.close();return fileData;}
}
前端jQuery
javascript">function downloadFile(filePath) {$.ajax({url: '/download',type: 'GET',data: { filePath: filePath },xhrFields: {responseType: 'blob'  // Important to handle binary data},success: function(data, status, xhr) {// Create a download link for the blob datavar blob = new Blob([data], { type: xhr.getResponseHeader('Content-Type') });var link = document.createElement('a');link.href = window.URL.createObjectURL(blob);link.download = 'filename.ext'; // You can set the default file name heredocument.body.appendChild(link);link.click();document.body.removeChild(link);},error: function(xhr, status, error) {console.error('File download failed:', status, error);}});
}

http://www.ppmy.cn/server/47669.html

相关文章

进程间通信(27000字超详解)

&#x1f30e;进程间通信 文章目录&#xff1a; 进程间通信 进程间通信简介       进程间通信目的       初识进程间通信       进程间通信的分类 匿名管道通信       认识管道       匿名管道       匿名管道测试       管道的四种…

OpenCV学习(4.1) 改变颜色空间

1.目标 在本教程中&#xff0c;你将学习如何将图像从一个色彩空间转换到另一个&#xff0c;像BGR↔灰色&#xff0c;BGR↔HSV等除此之外&#xff0c;我们还将创建一个应用程序&#xff0c;以提取视频中的彩色对象你将学习以下功能&#xff1a;cv2.cvtColor&#xff0c;**cv2.i…

LeetCode刷题 | Day 2 最长严格递增或递减子列表(Longest Increasing or Decreasing SubList)

LeetCode刷题 | Day 2 最长严格递增或递减子列表(Longest Increasing Decreasing SubList) 文章目录 LeetCode刷题 | Day 2 最长严格递增或递减子列表(Longest Increasing Decreasing SubList)前言一、题目概述二、解题方法2.1 动态规划思想2.1.1 思路讲解2.1.2 伪代码 + 逐…

云计算-高级云资源配置(Advanced Cloud Provisioning)

向Bucket添加公共访问&#xff08;Adding Public Access to Bucket&#xff09; 在模块5中&#xff0c;我们已经看到如何使用CloudFormation创建和更新一个Bucket。现在我们将进一步更新该Bucket&#xff0c;添加公共访问权限。我们在模块5中使用的模板&#xff08;third_templ…

Jenkins常用插件与应用详解

&#x1f345; 视频学习&#xff1a;文末有免费的配套视频可观看 &#x1f345; 点击文末小卡片&#xff0c;免费获取软件测试全套资料&#xff0c;资料在手&#xff0c;涨薪更快 Jenkins是一个平台我们通过安装插件来解决我们想要完成的任务 1、Jenkins常用插件 Allure&#…

竹纤维家装元宇宙:虚拟空间与绿色生活的融合

在全球化和科技迅速发展的今天&#xff0c;元宇宙作为一种全新的互联网应用和社会形态&#xff0c;正逐步渗透到人们生活的各个方面。特别是在家装行业&#xff0c;竹纤维作为一种新型环保材料&#xff0c;结合元宇宙的概念&#xff0c;正在引领一场绿色生活的革命。 ### 一、…

JavaSE——【逻辑控制】(知识)

目录 前言 一、顺序结构 二、分支结构 三、循环结构 总结 前言 公元 3050 年&#xff0c;地球的科技已经发展到令人难以想象的地步。这天&#xff0c;艾米莉在自己的房间里启动了最新的虚拟旅行装置&#xff0c;下一秒&#xff0c;她发现小奥奇的博客更新了。立即放弃了虚…

实验名称:函数练习2

你是蛤蟆秧子跟着甲鱼转,装王八孙子。这是我今天听到最牛逼的一句话。 目录 一、实验目的 二、实验环境 三、实验步骤 四、实验结果 1.系统的增删改等都需要先登录后才能操作。 编写装饰器用于登录验证&#xff0c;再对增删改进行装饰&#xff0c;测试登录验证装饰器是…