java项目使用jsch下载ftp文件

pom

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

demo1:main方法直接下载

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:页面按钮调接口下载

后端
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

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
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 data
            var 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 here
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        },
        error: function(xhr, status, error) {
            console.error('File download failed:', status, error);
        }
    });
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Kotlin使用JSch()登录FTP服务器并下载大型Excel文件的示例代码: ```kotlin import com.jcraft.jsch.ChannelSftp import com.jcraft.jsch.JSch import com.jcraft.jsch.Session import java.io.File import java.io.FileOutputStream fun main() { val jsch = JSch() val session = jsch.getSession("username", "ftp.example.com", 22) session.setPassword("password") session.setConfig("StrictHostKeyChecking", "no") session.connect() val channel = session.openChannel("sftp") as ChannelSftp channel.connect() val remoteFilePath = "/path/to/largefile.xlsx" val localFilePath = "/path/to/localfile.xlsx" val remoteFileSize = channel.stat(remoteFilePath).size val output = FileOutputStream(File(localFilePath)) val bufferSize = 1024 * 1024 // 1MB buffer var totalBytesRead: Long = 0 var bytesRead: Int val buffer = ByteArray(bufferSize) val input = channel.get(remoteFilePath) while (true) { bytesRead = input.read(buffer, 0, bufferSize) if (bytesRead == -1) break output.write(buffer, 0, bytesRead) totalBytesRead += bytesRead println("Downloaded ${totalBytesRead / 1024} KB / ${remoteFileSize / 1024} KB") } input.close() output.close() channel.disconnect() session.disconnect() } ``` 这段代码使用JSch库来连接FTP服务器并下载文件。首先,我们创建了一个JSch实例并使用用户名和密码创建了一个会话。然后,我们打开了一个sftp通道并连接到FTP服务器。 接下来,我们指定了远程文件的路径和本地文件的路径。我们使用ChannelSftp的stat()方法获取了远程文件的大小,并创建了一个FileOutputStream来写入本地文件。 我们使用了一个1MB缓冲区来逐块下载文件。我们读取缓冲区中的数据,并写入到本地文件中。我们使用了一个计数器来跟踪我们已经下载了多少数据,并在每次下载后打印出来。 最后,我们关闭了输入和输出流,并断开了通道和会话的连接。 请注意,这段代码假设您的FTP服务器可以通过SSH连接,并且您已经将JSch库添加到您的项目中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值