pom依赖包

1 <dependency>
2      <groupId>commons-net</groupId>
3       <artifactId>commons-net</artifactId>
4       <version>3.6</version>
5 </dependency>

 

ftp登录初始化

 private FTPClient connectFtpServer(){
        FTPClient ftpClient = new FTPClient();
        ftpClient.setConnectTimeout(1000*30);//设置连接超时时间
        ftpClient.setControlEncoding("utf-8");//设置ftp字符集
        ftpClient.enterLocalPassiveMode();//设置被动模式,文件传输端口设置
        try {
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//设置文件传输模式为二进制,可以保证传输的内容不会被改变
            ftpClient.connect(url);
            ftpClient.login(userName,password);
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)){
                LOGGER.error("connect ftp {} failed",url);
                ftpClient.disconnect();
                return null;
            }
            LOGGER.info("replyCode==========={}",replyCode);
        } catch (IOException e) {
            LOGGER.error("connect fail ------->>>{}",e.getCause());
            return null;
        }
        return ftpClient;
}

 

ftp上传文件

 1  /**
 2      *
 3      * @param inputStream 待上传文件的输入流
 4      * @param originName 文件保存时的名字
 5      */
 6     public void uploadFile(InputStream inputStream, String originName){
 7         FTPClient ftpClient = connectFtpServer();
 8         if (ftpClient == null){
 9             return;
10         }
11 
12         try {
13             ftpClient.changeWorkingDirectory(remoteDir);//进入到文件保存的目录
14             Boolean isSuccess = ftpClient.storeFile(originName,inputStream);//保存文件
15             if (!isSuccess){
16                 throw new BusinessException(ResponseCode.UPLOAD_FILE_FAIL_CODE,originName+"---》上传失败!");
17             }
18             LOGGER.info("{}---》上传成功!",originName);
19             ftpClient.logout();
20         } catch (IOException e) {
21             LOGGER.error("{}---》上传失败!",originName);
22             throw new BusinessException(ResponseCode.UPLOAD_FILE_FAIL_CODE,originName+"上传失败!");
23         }finally {
24             if (ftpClient.isConnected()){
25                 try {
26                     ftpClient.disconnect();
27                 } catch (IOException e) {
28                     LOGGER.error("disconnect fail ------->>>{}",e.getCause());
29                 }
30             }
31         }
32     }
View Code

相关文章:

  • 2022-02-06
  • 2021-10-22
  • 2021-05-26
  • 2022-01-05
  • 2022-01-07
  • 2021-11-02
  • 2021-06-14
  • 2021-12-26
猜你喜欢
  • 2022-12-23
  • 2022-01-30
  • 2021-12-04
  • 2021-12-22
  • 2022-02-18
  • 2021-08-20
相关资源
相似解决方案