java项目利用jsch下载ftp文件

张春  金牌会员 | 2024-6-27 00:20:39 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 571|帖子 571|积分 1713

pom
  1. <dependency>
  2.     <groupId>com.jcraft</groupId>
  3.     <artifactId>jsch</artifactId>
  4.     <version>0.1.55</version>
  5. </dependency>
复制代码
demo1:main方法直接下载

  1. package com.example.controller;
  2. import com.jcraft.jsch.*;
  3. import java.io.File;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. public class JSchSFTPFileTransfer {
  7.     public static void main(String[] args) {
  8.         String host = "10.*.*.*";//服务器地址
  9.         String user = "";//用户
  10.         String password = "";//密码
  11.         int port = 22;//端口
  12.         String remoteFilePath = "/home/*/*/ps.xlsx";//拉取文件的路径
  13.         String localFilePath = "C:\\Users\\*\\Downloads\\ps.xlsx";//下载到本地路径
  14.         JSch jsch = new JSch();
  15.         // 初始化对象
  16.         Session session = null;
  17.         ChannelSftp sftpChannel = null;
  18.         InputStream inputStream = null;
  19.         OutputStream outputStream = null;
  20.         try {
  21.             // 创建会话
  22.             session = jsch.getSession(user, host, port);
  23.             session.setConfig("StrictHostKeyChecking", "no");
  24.             session.setPassword(password);
  25.             session.connect();
  26.             // 打开 SFTP 通道
  27.             sftpChannel = (ChannelSftp) session.openChannel("sftp");
  28.             sftpChannel.connect();
  29.             //创建本地路径
  30.             int lastSlashIndex = remoteFilePath.lastIndexOf("/");
  31.             String path = remoteFilePath.substring(0, lastSlashIndex);
  32.             File file = new File(path);
  33.             if (!file.exists()) {
  34.                 try {
  35.                     file.mkdirs();
  36.                 } catch (Exception e) {
  37.                     System.out.println("=====jSchSFTPFileTransfer创建文件夹失败!====");
  38.                 }
  39.             }
  40.             // 下载文件
  41.             inputStream = sftpChannel.get(remoteFilePath);
  42.             // 上传文件到本地
  43.             outputStream = new java.io.FileOutputStream(localFilePath);
  44.             byte[] buffer = new byte[1024];
  45.             int bytesRead;
  46.             while ((bytesRead = inputStream.read(buffer)) != -1) {
  47.                 outputStream.write(buffer, 0, bytesRead);
  48.             }
  49.             System.out.println("=====jSchSFTPFileTransfer文件下载成功!===="+localFilePath);
  50.         } catch (JSchException | SftpException | java.io.IOException e) {
  51.             e.printStackTrace();
  52.         } finally {
  53.             // 关闭流、通道和会话
  54.             if (inputStream != null) {
  55.                 try {
  56.                     inputStream.close();
  57.                 } catch (java.io.IOException e) {
  58.                     e.printStackTrace();
  59.                 }
  60.             }
  61.             if (outputStream != null) {
  62.                 try {
  63.                     outputStream.close();
  64.                 } catch (java.io.IOException e) {
  65.                     e.printStackTrace();
  66.                 }
  67.             }
  68.             if (sftpChannel != null && sftpChannel.isConnected()) {
  69.                 sftpChannel.disconnect();
  70.             }
  71.             if (session != null && session.isConnected()) {
  72.                 session.disconnect();
  73.             }
  74.         }
  75.     }
  76. }
复制代码
demo2:页面按钮调接口下载

后端

  1. package com.example.controller;
  2. import com.example.common.utils.SFTPUtil;
  3. import com.jcraft.jsch.SftpException;
  4. import org.springframework.http.ResponseEntity;
  5. import org.springframework.http.HttpHeaders;
  6. import org.springframework.http.MediaType;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. @RestController
  10. public class testController {
  11.     @GetMapping(value = "/export")
  12.     public ResponseEntity<byte[]> empController(String remotePath) throws Exception {
  13. //        remotePath = "/home/fr/zycpzb/ps.xlsx";
  14.         String host = "10.1.16.92";
  15.         int port = 22;
  16.         String userName = "fr";
  17.         String password = "Lnbi#0Fr";
  18.         SFTPUtil sftp = new SFTPUtil(userName, password, host, port);
  19.         sftp.login();
  20.         try {
  21.             byte[] buff = sftp.download(remotePath);
  22.             HttpHeaders headers = new HttpHeaders();
  23.             headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
  24.             headers.setContentDispositionFormData("attachment", "ps.xlsx");
  25.             return ResponseEntity.ok().headers(headers).body(buff);
  26.         } catch (SftpException e) {
  27.             e.printStackTrace();
  28.             return ResponseEntity.status(500).body(null);
  29.         }finally {
  30.             sftp.logout();
  31.         }
  32.     }
  33. }
复制代码
SFTPUtil
  1. package com.example.common.utils;
  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.util.*;
  8. import com.jcraft.jsch.*;
  9. import org.apache.commons.io.IOUtils;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. /**
  13. *
  14. * @ClassName: SFTPUtil
  15. * @Description: sftp连接工具类
  16. * @version 1.0.0
  17. */
  18. public class SFTPUtil {
  19.     private transient Logger log = LoggerFactory.getLogger(this.getClass());
  20.     private ChannelSftp sftp;
  21.     private Session session;
  22.     /**
  23.      * FTP 登录用户名
  24.      */
  25.     private String username;
  26.     /**
  27.      * FTP 登录密码
  28.      */
  29.     private String password;
  30.     /**
  31.      * 私钥
  32.      */
  33.     private String privateKey;
  34.     /**
  35.      * FTP 服务器地址IP地址
  36.      */
  37.     private String host;
  38.     /**
  39.      * FTP 端口
  40.      */
  41.     private int port;
  42.     /**
  43.      * 构造基于密码认证的sftp对象
  44.      *
  45.      * @param username
  46.      * @param password
  47.      * @param host
  48.      * @param port
  49.      */
  50.     public SFTPUtil(String username, String password, String host, int port) {
  51.         this.username = username;
  52.         this.password = password;
  53.         this.host = host;
  54.         this.port = port;
  55.     }
  56.     /**
  57.      * 构造基于秘钥认证的sftp对象
  58.      *
  59.      * @param username
  60.      * @param host
  61.      * @param port
  62.      * @param privateKey
  63.      */
  64.     public SFTPUtil(String username, String host, int port, String privateKey) {
  65.         this.username = username;
  66.         this.host = host;
  67.         this.port = port;
  68.         this.privateKey = privateKey;
  69.     }
  70.     public SFTPUtil() {
  71.     }
  72.     /**
  73.      * 连接sftp服务器
  74.      *
  75.      * @throws Exception
  76.      */
  77.     public void login() {
  78.         try {
  79.             JSch jsch = new JSch();
  80.             if (privateKey != null) {
  81.                 jsch.addIdentity(privateKey);// 设置私钥
  82.                 log.info("sftp connect,path of private key file:{}", privateKey);
  83.             }
  84.             log.info("sftp connect by host:{} username:{}", host, username);
  85.             session = jsch.getSession(username, host, port);
  86.             log.info("Session is build");
  87.             if (password != null) {
  88.                 session.setPassword(password);
  89.             }
  90.             Properties config = new Properties();
  91.             config.put("StrictHostKeyChecking", "no");
  92.             session.setConfig(config);
  93.             session.connect();
  94.             log.info("Session is connected");
  95.             Channel channel = session.openChannel("sftp");
  96.             channel.connect();
  97.             log.info("channel is connected");
  98.             sftp = (ChannelSftp) channel;
  99.             log.info(String.format("sftp server host:[%s] port:[%s] is connect successfull", host, port));
  100.         } catch (JSchException e) {
  101.             log.error("Cannot connect to specified sftp server : {}:{} \n Exception message is: {}", new Object[]{host, port, e.getMessage()});
  102.         }
  103.     }
  104.     /**
  105.      * 关闭连接 server
  106.      */
  107.     public void logout() {
  108.         if (sftp != null) {
  109.             if (sftp.isConnected()) {
  110.                 sftp.disconnect();
  111.                 log.info("sftp is closed already");
  112.             }
  113.         }
  114.         if (session != null) {
  115.             if (session.isConnected()) {
  116.                 session.disconnect();
  117.                 log.info("sshSession is closed already");
  118.             }
  119.         }
  120.     }
  121.     /**
  122.      * 下载文件
  123.      *
  124.      * @param directory
  125.      *            下载目录
  126.      * @param downloadFile
  127.      *            下载的文件
  128.      * @param saveFile
  129.      *            存在本地的路径
  130.      * @throws SftpException
  131.      * @throws FileNotFoundException
  132.      * @throws Exception
  133.      */
  134.     public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException{
  135.         if (directory != null && !"".equals(directory)) {
  136.             sftp.cd(directory);
  137.         }
  138.         File file = new File(saveFile);
  139.         sftp.get(downloadFile, new FileOutputStream(file));
  140.         log.info("file:{} is download successful" , downloadFile);
  141.     }
  142.     /**
  143.      * 下载文件
  144.      * @param directory 下载目录
  145.      * @param downloadFile 下载的文件名
  146.      * @return 字节数组
  147.      * @throws SftpException
  148.      * @throws IOException
  149.      * @throws Exception
  150.      */
  151.     public byte[] download(String directory, String downloadFile) throws SftpException, IOException{
  152.         if (directory != null && !"".equals(directory)) {
  153.             sftp.cd(directory);
  154.         }
  155.         InputStream is = sftp.get(downloadFile);
  156.         byte[] fileData = IOUtils.toByteArray(is);
  157.         log.info("file:{} is download successful" , downloadFile);
  158.         return fileData;
  159.     }
  160.     /**
  161.      * 下载文件
  162.      * @param directory 下载的文件名
  163.      * @return 字节数组
  164.      * @throws SftpException
  165.      * @throws IOException
  166.      * @throws Exception
  167.      */
  168.     public byte[] download(String directory) throws SftpException, IOException{
  169.         InputStream is = sftp.get(directory);
  170.         byte[] fileData = IOUtils.toByteArray(is);
  171.         log.info("file:{} is download successful" , directory);
  172.         is.close();
  173.         return fileData;
  174.     }
  175. }
复制代码
前端jQuery

  1. function downloadFile(filePath) {
  2.     $.ajax({
  3.         url: '/download',
  4.         type: 'GET',
  5.         data: { filePath: filePath },
  6.         xhrFields: {
  7.             responseType: 'blob'  // Important to handle binary data
  8.         },
  9.         success: function(data, status, xhr) {
  10.             // Create a download link for the blob data
  11.             var blob = new Blob([data], { type: xhr.getResponseHeader('Content-Type') });
  12.             var link = document.createElement('a');
  13.             link.href = window.URL.createObjectURL(blob);
  14.             link.download = 'filename.ext'; // You can set the default file name here
  15.             document.body.appendChild(link);
  16.             link.click();
  17.             document.body.removeChild(link);
  18.         },
  19.         error: function(xhr, status, error) {
  20.             console.error('File download failed:', status, error);
  21.         }
  22.     });
  23. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

张春

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表