FTP上传文件到云服务器上的工具类

关于FTP上传文件到云服务器上的工具类
首先导入两个包 pom.xml

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.6</version>
</dependency>
<dependency>  
  <groupId>com.jcraft</groupId>  
  <artifactId>jsch</artifactId>  
  <version>0.1.49</version>  
</dependency>

或者你可以去下载频道下载
java类

public class FTP {

    private static String rootName = "连接服务器的登录名";
    private static String host = "主机名";
    private static String password = "连接密码";
    private static String rootPath = "/opt/images";//存放图片的根目录
    /**
     * 获取连接
     */
    public static ChannelSftp getChannel() throws Exception{
        JSch jsch = new JSch();  
        Session sshSession = jsch.getSession(rootName,host,22);//->ssh root@host:port  
        sshSession.setPassword(password);//密码  

        Properties sshConfig = new Properties();  
        sshConfig.put("StrictHostKeyChecking", "no");  
        sshSession.setConfig(sshConfig);  
        sshSession.connect(); 

        Channel channel = sshSession.openChannel("sftp");  
        channel.connect();  

        ChannelSftp sftp = (ChannelSftp) channel;
        return sftp;
    }

    /**
     * ftp上传图片
     * @param inputStream 图片io流
     * @param imagePath 路径,不存在就创建目录
     * @param imagesName 图片名称
     */
    public static void putImages(InputStream inputStream,String imagePath,String imagesName){
        try {
            ChannelSftp sftp = getChannel();
            String path = rootPath+imagePath+"/";
            createDir(path,sftp);
            sftp.put(inputStream, path + imagesName);
            System.out.println("创建成功");
            sftp.quit();
            sftp.exit();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    /**
     * 创建目录
     */
    public static void createDir(String path,ChannelSftp sftp) throws SftpException{
        String[] folders = path.split("/");
        sftp.cd("/");
        for ( String folder : folders ) {
            if ( folder.length() > 0 ) {
                try {
                    sftp.cd( folder );
                }catch ( SftpException e ) {
                    sftp.mkdir( folder );
                    sftp.cd( folder );
                }
            }
        }
    }

    /**
     * 删除图片
     * @param inputStream
     * @param imagesName
     */
    public static void delImages(String imagesName){
        try {
            ChannelSftp sftp = getChannel();
            String path = rootPath + imagesName;
            sftp.rm(path);
            sftp.quit();
            sftp.exit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值