1. 程式人生 > >SFTP檔案下載(由於SFTP有許可權設定,本地ip又不固定,所以為測試伺服器IP開通許可權,把檔案下載到測試伺服器,再用流讀到本地)

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();
    }
}