• springboot集成ftp


    springboot集成ftp

    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

    ftp读取文件,并转成base64

     1 /**
     2      *  读ftp上的文件,并将其转换成base64
     3      * @param remoteFileName ftp服务器上的文件名
     4      * @return
     5      */
     6  public String readFileToBase64(String remoteFileName){
     7         FTPClient ftpClient = connectFtpServer();
     8         if (ftpClient == null){
     9             return null;
    10         }
    11 
    12         String base64 = "";
    13         InputStream inputStream = null;
    14 
    15         try {
    16             ftpClient.changeWorkingDirectory(remoteDir);
    17             FTPFile[] ftpFiles = ftpClient.listFiles(remoteDir);
    18             Boolean flag = false;
    19             //遍历当前目录下的文件,判断要读取的文件是否在当前目录下
    20             for (FTPFile ftpFile:ftpFiles){
    21                 if (ftpFile.getName().equals(remoteFileName)){
    22                     flag = true;
    23                 }
    24             }
    25 
    26             if (!flag){
    27                 LOGGER.error("directory:{}下没有 {}",remoteDir,remoteFileName);
    28                 return null;
    29             }
    30             //获取待读文件输入流
    31             inputStream = ftpClient.retrieveFileStream(remoteDir+remoteFileName);
    32 
    33             //inputStream.available() 获取返回在不阻塞的情况下能读取的字节数,正常情况是文件的大小
    34             byte[] bytes = new byte[inputStream.available()];
    35 
    36             inputStream.read(bytes);//将文件数据读到字节数组中
    37             BASE64Encoder base64Encoder = new BASE64Encoder();
    38             base64 = base64Encoder.encode(bytes);//将字节数组转成base64字符串
    39             LOGGER.info("read file {} success",remoteFileName);
    40             ftpClient.logout();
    41         } catch (IOException e) {
    42             LOGGER.error("read file fail ----->>>{}",e.getCause());
    43             return null;
    44         }finally {
    45             if (ftpClient.isConnected()){
    46                 try {
    47                     ftpClient.disconnect();
    48                 } catch (IOException e) {
    49                     LOGGER.error("disconnect fail ------->>>{}",e.getCause());
    50                 }
    51             }
    52 
    53             if (inputStream != null){
    54                 try {
    55                     inputStream.close();
    56                 } catch (IOException e) {
    57                     LOGGER.error("inputStream close fail -------- {}",e.getCause());
    58                 }
    59             }
    60 
    61         }
    62 
    63         return base64;
    64 
    65  }
    View Code

    ftp下载文件

     1     /**
     2      * 文件下载
     3      * @param remoteFileName ftp上的文件名
     4      * @param localFileName 本地文件名
     5      */
     6 public void download(String remoteFileName,String localFileName){
     7         FTPClient ftpClient = connectFtpServer();
     8         if (ftpClient == null){
     9             return ;
    10         }
    11 
    12         OutputStream outputStream = null;
    13 
    14         try {
    15             ftpClient.changeWorkingDirectory(remoteDir);
    16             FTPFile[] ftpFiles = ftpClient.listFiles(remoteDir);
    17             Boolean flag = false;
    18             //遍历当前目录下的文件,判断是否存在待下载的文件
    19             for (FTPFile ftpFile:ftpFiles){
    20                 if (ftpFile.getName().equals(remoteFileName)){
    21                     flag = true;
    22                     break;
    23                 }
    24             }
    25 
    26             if (!flag){
    27                 LOGGER.error("directory:{}下没有 {}",remoteDir,remoteFileName);
    28                 return ;
    29             }
    30 
    31             outputStream = new FileOutputStream(localDir+localFileName);//创建文件输出流
    32 
    33             Boolean isSuccess = ftpClient.retrieveFile(remoteFileName,outputStream); //下载文件
    34             if (!isSuccess){
    35                 LOGGER.error("download file 【{}】 fail",remoteFileName);
    36             }
    37 
    38             LOGGER.info("download file success");
    39             ftpClient.logout();
    40         } catch (IOException e) {
    41             LOGGER.error("download file 【{}】 fail ------->>>{}",remoteFileName,e.getCause());
    42         }finally {
    43             if (ftpClient.isConnected()){
    44                 try {
    45                     ftpClient.disconnect();
    46                 } catch (IOException e) {
    47                     LOGGER.error("disconnect fail ------->>>{}",e.getCause());
    48                 }
    49             }
    50 
    51             if (outputStream != null){
    52                 try {
    53                     outputStream.close();
    54                 } catch (IOException e) {
    55                     LOGGER.error("outputStream close fail ------->>>{}",e.getCause());
    56                 }
    57             }
    58         }
    59     }
    View Code

    ftp客户端与服务端之间数据传输,主动模式和被动模式

    请移至这个哥们的博文中查看,https://www.cnblogs.com/mawanglin2008/articles/3607767.html,写的非常好。

    主动模式:ftp客户端产生一个随机端口,并告知ftp服务端,最后服务端的20端口会与这个随机端口建立连接,进行数据传输

    被动模式:ftp服务端产生一个随机端口,并告知ftp客户端,最后客户端与这个随机端口建立连接,进行数据传输

  • 相关阅读:
    天生我牛必有用
    struts1.x+spring2.5+JPA(hibernate)整合
    Struts2拦截器
    使用Apache的commonscodes加密
    解放鞋 Ospop解放鞋
    告别2008 明天2009
    异常java.lang.UnsupportedClassVersionError: Bad version number in .class file
    C#中的Process类使用
    C#中使用MD5加密
    Struts2 Action(1)
  • 原文地址:https://www.cnblogs.com/sxqjava/p/10335451.html
Copyright © 2020-2023  润新知