zoukankan      html  css  js  c++  java
  • Java 上传文件到ftp服务器

    项目中需要上传工艺文件到ftp服务器的功能,一边百度,一边摸索,记录一下;

    框架:SpringBoot 2.1.5.RELEASE

    Java版本:jdk1.8

    jar包依赖:

            <!-- file upload -->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.1</version>
            </dependency>
            <!-- file upload -->
    
            <!-- ftp begin -->
            <dependency>
                <groupId>commons-net</groupId>
                <artifactId>commons-net</artifactId>
                <version>3.5</version>
            </dependency>
            <!-- ftp end -->
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>

    代码:

            FTPClient ftp = new FTPClient();
            int reply;
            try {
                ftp.connect("127.0.0.1", 21);
                //5、输入账号和密码进行登录
                ftp.login("username", "password");
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                ftp.enterLocalPassiveMode();
                ftp.setControlEncoding("GBK");
                reply = ftp.getReplyCode();
                System.out.println("状态码: " + reply); //连接ftp返回状态码
                // 判断是否连接成功
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    System.out.println("连接ftp失败");
                }
    
                // 判断文件夹是否存在
                if(!ftp.changeWorkingDirectory("/test")) {
                    System.out.println("/test 路径不存在!");
                    // 不存在创建文件夹
                    boolean makeResult = ftp.makeDirectory("/test");
                    System.out.println("makeResult: " + makeResult);
                } else {
                    System.out.println("/test 路径存在!");
                }
    
                if(!ftp.changeWorkingDirectory("/test")) {
                    System.out.println("/test 路径不存在!");
                } else {
                    System.out.println("/test 路径存在!");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    注意:因为ftp服务器是在windows server 2012上搭建的,我以为路径应该是D:/ftp,是错的,正确路径/file/routeLine这样的;

  • 相关阅读:
    Java编程思想读书笔记 第十章 内部类
    利用lambda和条件表达式构造匿名递归函数
    概率论与数理统计-课程小报告
    leetcode226 翻转二叉树
    leetcode199 二叉树的右视图
    leetcode114- 二叉树展开为链表
    leetcode145 二叉树的后序遍历 特别注意迭代
    leet144 二叉树的前序遍历
    leetcode113 路径总和2 特别关注
    leetcode 112 路径总和 特别关注
  • 原文地址:https://www.cnblogs.com/mxh-java/p/14136936.html
Copyright © 2011-2022 走看看