0
点赞
收藏
分享

微信扫一扫

使用SFTP&FTP将数据内容文件上传到三方服务器

前行的跋涉者 2022-02-10 阅读 97

需求:最近一个需求变更,刚开始是将订单导出数据导出指定格式txt文件,后来变更为将订单文件直接推送到对方服务器。

思路:先将数据内容输出到服务器上,在将文件推送到三方服务器。推送完成记得删除暂存服务器上的文件

准备工作:

	我们会由系统人员配置白名单,设置acl访问限制,拿到需要上传的服务器FTP的地址,端口号,FTP账号和密码,上传路径等,保证我们系统能够链接到对方服务器。

代码实现:

1.依赖:

SFTP和FTP的jar包不同 ,根据个人需求只要一个就可以了

<!--FTP包-->
<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.5</version>
</dependency>
 
 
<!--SFTP包-->
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.54</version>
</dependency>

2.数据输出到本地服务器

public String writeToTxtSFTP(B2bOrderDetailVO orderDetail, List<B2bOrderGiftInfo> giftInfos) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        /*实例化日期用于生成文件名称*/
        String fileName = simpleDateFormat.format(new Date());
        /*在相应的路径下创建对应的文件夹*/
        String filePath = FILE_PATH_PREFIX + fileName + FILE_PATH_SUFFIX;
        FileOutputStream fileOutputStream = null;
        //输出数据
        try {
            File file = new File(FILE_PATH_PREFIX);
            if (!file.exists()) {
                file.mkdirs();
            }
            fileOutputStream =  new FileOutputStream(filePath,false);
            //获取输出文本
            String text = getOutputText(orderDetail, giftInfos);
            log.info("sftp上传订单SAP数据内容为:"+text);
            fileOutputStream.write(text.getBytes());
            fileOutputStream.flush();
        } catch (Exception e) {
            log.error("订单SAP格式文件上传失败,失败信息{}", e);
        } finally {
            try {
                fileOutputStream.close();
            } catch (Exception e) {
                log.error("关闭通道失败,失败信息{}", e);
            }
        }
        return filePath;
    }

3.sftp上传

我用的sftp方式所以首先需要建立SFTP类

public class SFTP {
    private Session session;//会话
    private Channel channel;//连接通道
    private ChannelSftp sftp;// sftp操作类


    public Session getSession() {
        return session;
    }
    public void setSession(Session session) {
        this.session = session;
    }
    public Channel getChannel() {
        return channel;
    }
    public void setChannel(Channel channel) {
        this.channel = channel;
    }
    public ChannelSftp getSftp() {
        return sftp;
    }
    public void setSftp(ChannelSftp sftp) {
        this.sftp = sftp;
    }
}

SFTP链接的工具类

@Slf4j
public class SFTPChannel {

    //ftp服务器IP地址
    private static String ftpHost = "*****";
    //ftp服务器的端口号
    private static int ftpPort = 22;
    //ftp服务器用户名
    private static String ftpUserName = "******";
    //ftp服务器密码
    private static String ftpPassword = "******";
    //上传服务器路径
    private static String ftpLocation = "/ORDER/";

    /**
     * 连接ftp/sftp服务器
     * @param
     */
    public static void getConnect(SFTP s) throws Exception {

        Session session = null;
        Channel channel = null;
        ChannelSftp sftp = null;// sftp操作类

        JSch jsch = new JSch();

        session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
        session.setPassword(ftpPassword);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no"); // 不验证 HostKey
        session.setConfig(config);
        try {
            session.connect();
        } catch (Exception e) {
            if (session.isConnected()) {
                session.disconnect();
            }
            log.error("连接服务器失败:{}",e);
            log.error("连接服务器失败,请检查主机[" + ftpHost + "],端口[" + ftpPort
                    + "],用户名[" + ftpUserName + "],端口[" + ftpPort
                    + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
        }
        channel = session.openChannel("sftp");
        try {
            channel.connect();
        } catch (Exception e) {
            if (channel.isConnected()) {
                channel.disconnect();
            }
            log.error("连接服务器失败,请检查主机[" + ftpHost + "],端口[" + ftpPort
                    + "],用户名[" + ftpUserName + "],密码是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
        }
        sftp = (ChannelSftp) channel;

        s.setChannel(channel);
        s.setSession(session);
        s.setSftp(sftp);
        log.info("sftp链接成功");
    }

    /**
     * 断开连接
     *
     */
    public static void disConn(Session session,Channel channel,ChannelSftp sftp)throws Exception{
        if(null != sftp){
            sftp.disconnect();
            sftp.exit();
            sftp = null;
        }
        if(null != channel){
            channel.disconnect();
            channel = null;
        }
        if(null != session){
            session.disconnect();
            session = null;
        }
    }
}

上传文件


    /**
     * 上传文件
     * @param uploadFile 要上传的文件全路径
     */
    public static void upload(String uploadFile) throws Exception {

        SFTP s=new SFTP();
        //建立连接
        getConnect(s);
        Session session = s.getSession();
        Channel channel = s.getChannel();
        // sftp操作类
        ChannelSftp sftp = s.getSftp();
        InputStream in = null;
        try {
            File file = new File(uploadFile);
            in= new FileInputStream(file);

            //如果对方的账号密码只能访问固定的文件夹的话,那就直接file.getName()
            // 如果有固定的路径的话,那就写对方给你的上传至文件夹的全路径
            sftp.put(in, ftpLocation + file.getName());
        } catch (Exception e) {
            log.error("sftp上传问题很大"+e,e.getMessage(),e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                log.error("关闭通道失败,失败信息{}", e);
            }
            disConn(session,channel,sftp);
            log.info("关闭sftp链接成功");
        }
    }
举报

相关推荐

0 条评论