SFTP文件下载(由于SFTP有权限设置,本地ip又不固定,所以为测试服务器IP开通权限,把文件下载到测试服务器,再用流读到本地)

1.工具类

import java.util.Properties;
import org.apache.log4j.Logger;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SFTPUtils {
  private static Logger log = Logger.getLogger(SFTPUtils.class.getName());
  /*
* 从SFTP服务器下载文件
* 
* @param ftpHost SFTP IP地址
* 
* @param ftpUserName SFTP 用户名
* 
* @param ftpPassword SFTP用户名密码
* 
* @param ftpPort SFTP端口
* 
* @param ftpPath SFTP服务器中文件所在路径 格式: ftptest/aa
* 
* @param localPath 下载到本地的位置 格式:H:/download
* 
* @param fileName 文件名称
*/
public static void downloadSftpFile(String ftpHost, String ftpUserName,
String ftpPassword, int ftpPort, String ftpPath, String localPath,
String fileName) throws JSchException {
    Session session = null;
    Channel channel = null;
 
    JSch jsch = new JSch();
    session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
    session.setPassword(ftpPassword);
    session.setTimeout(100000);
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect();
 
    channel = session.openChannel("sftp");
    channel.connect();
    ChannelSftp chSftp = (ChannelSftp) channel;
 
 
    try {
        chSftp.get(ftpPath, localPath);
    } catch (Exception e) {
        e.printStackTrace();
        log.info("download error.");
    } finally {
        chSftp.quit();
        channel.disconnect();
        session.disconnect();
    }
  }

}

2、下载用例

/**
* 把SFTP文件下载到Linux服务的/opt/enloan/目录,然后在使用流读取
* @param filename 文件名
* @param path 源文件路径
* @param response

* @return

*Constant.FILEPATH  为Linux服务的目录为:/opt/enloan/

*/
@RequestMapping("proofRecord/download")
public void proofRecordDown(String fileName, String path,HttpServletResponse response) {
    try {
        SFTPUtils.downloadSftpFile("218.76.54.205", "sxhuaan", "sxhuaan@123", 20022,     path, Constant.FILEPATH, fileName);

        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
        "attachment;fileName=" + java.net.URLEncoder.encode(fileName, "utf-8"));
        File file = new File(Constant.FILEPATH+fileName);
        InputStream inputStream = new FileInputStream(file);
        OutputStream os = response.getOutputStream();
        byte[] b = new byte[2048];
        int length;
        while ((length = inputStream.read(b)) > 0) {
            os.write(b, 0, length);
        }
        os.close();
        inputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

猜你喜欢

转载自blog.csdn.net/L15810356216/article/details/80927017
今日推荐