项目中需要上传工艺文件到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这样的;