当前位置: 首页 > 工具软件 > Ftp Dot Net > 使用案例 >

ftp上传下载工具类

佘俊茂
2023-12-01

1.application.yml配置

ftp:
  host: 192.168.10.236
  port: 21
  username: longjinfile
  password: 123456
  filepath: /
file:
  fileTmpPath: /opt/javaapp/tmp/
  ftpBasePath: /case

2.工具类:

package net.longjin.file.service.impl;

import net.longjin.comm.utils.AsposeWordsUtils;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Component
public class FileUtils {

   private static final Logger log = LoggerFactory.getLogger(FileUtils.class);

   @Value("${ftp.username}")
   private String userName;

   @Value("${ftp.password}")
   private String passWord;

   @Value("${ftp.host}")
   private String url;

   @Value("${ftp.port}")
   private int port;

   @Value("${file.fileTmpPath}")
   private String fileTmpPath;


   /**
    * 处理上传文件,如果是word格式就直接在本地转成PDF再上传到FTP上
    * @param file
    * @param remotePath
    * @param fileSaveName
    * @return
    * @throws IOException
    */
   public boolean  uploadFiles (MultipartFile file, String remotePath, String fileSaveName) throws IOException {
      String fileName = file.getOriginalFilename();
      String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
      if(suffix.equals("doc")||suffix.equals("docx")) {
         File dest = new File(fileTmpPath + fileSaveName);
         file.transferTo(dest);
         String pdfTmpName = getFileNameNoEx(fileSaveName)+".pdf";
         AsposeWordsUtils.doc2pdf(fileTmpPath+"/"+fileSaveName,fileTmpPath+"/"+pdfTmpName);
         File pdfFile = new File(fileTmpPath+"/"+pdfTmpName);
         InputStream is = new FileInputStream(pdfFile);
         boolean rs = uploadFile(is, remotePath, fileSaveName);
         dest.delete();
         pdfFile.delete();
         is.close();
         return rs;
      }else{
         boolean rs = uploadFile(file.getInputStream(), remotePath, fileSaveName);
         return rs ;
      }
   }

   /**
    * 处理图片上传,生成缩略图
    * @param remotePath  FTP路径
    * @param fileSaveName  FTP保存文件名称
    * @param thumbnail  FTP保存缩略图名称
    * @return
    * @throws IOException
    */
   public boolean  uploadPicFiles (String remotePath, String fileSaveName,String thumbnail) throws IOException {
      File dest = new File(fileTmpPath + fileSaveName);
      InputStream is = new FileInputStream(dest);
      //Thumbnails.of(fileTmpPath + fileSaveName).size(400,500).toFile(fileTmpPath+thumbnail);
      Thumbnails.of(fileTmpPath + fileSaveName).scale(1f).outputQuality(0.15f).toFile(fileTmpPath+thumbnail);
      File thumbnailTemp = new File(fileTmpPath + thumbnail);
      InputStream isTemp = new FileInputStream(thumbnailTemp);
      boolean rs = uploadFile(is, remotePath, fileSaveName);
      boolean trs = uploadFile(isTemp, remotePath, thumbnail);
      is.close();
      isTemp.close();
      thumbnailTemp.delete();
      if(rs&&trs){
         return true;
      }else{
         return false;
      }
   }

   /**
    * 获取文件的后缀名
    * @param filename
    * @return
    */
   public static String getFileNameNoEx(String filename) {
      if ((filename != null) && (filename.length() > 0)) {
         int dot = filename.lastIndexOf('.');
         if ((dot >-1) && (dot < (filename.length()))) {
            return filename.substring(0, dot);
         }
      }
      return filename;
   }


   /**
    * 上传文件到ftp
    * @param input
    * @param remotePath
    * @param fileSaveName
    * @return
    */
   public   boolean uploadFile(InputStream input,String remotePath,String fileSaveName){
      boolean success = false;
      FTPClient ftp = new FTPClient();
      try {
         createDirecroty(remotePath);//创建目录
         ftp.setControlEncoding("GBK");
         int reply;
         ftp.connect(url, port);// 连接FTP服务器
         ftp.login(userName, passWord);// 登录
         ftp.setControlEncoding("UTF-8"); // 中文支持
         reply = ftp.getReplyCode();
         if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
         }
         ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
         ftp.makeDirectory(remotePath);
         ftp.changeWorkingDirectory(remotePath);
         ftp.storeFile(fileSaveName,input);
         input.close();
         ftp.logout();
         success = true;
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         if (ftp.isConnected()) {
            try {
               ftp.disconnect();
            } catch (IOException ioe) {
            }
         }
      }
      return success;
   }

   /**
    * 从FTP上下载文件到本地临时目录保存
    * @param remotePath
    * @param fileSaveName
    * @param localTmpName
    * @return
    */
   public boolean downFile(String remotePath, String fileSaveName, String localTmpName) {
      boolean success = false;
      FTPClient ftp = new FTPClient();

      try {
         //remotePath = new String(remotePath.getBytes("GBK"),"iso-8859-1");
         int reply;
         ftp.connect(url, port);
         // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
         ftp.login(userName, passWord);// 登录
         ftp.setControlEncoding("UTF-8"); // 中文支持
         ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
         ftp.enterLocalPassiveMode();
         reply = ftp.getReplyCode();
         if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
         }
         log.info("remotePath:"+remotePath);
         ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
         File localFile = new File(fileTmpPath + "/" + localTmpName);
         log.info("本地保存:"+fileTmpPath + "/" + localTmpName);
         OutputStream is = new FileOutputStream(localFile);
         ftp.retrieveFile(fileSaveName, is);
         is.close();
         ftp.logout();
         success = true;
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         if (ftp.isConnected()) {
            try {
               ftp.disconnect();
            } catch (IOException ioe) {
            }
         }
      }
      return success;
   }


   public boolean isFTPFileExist(String filePath){
      FTPClient ftp = new FTPClient();
      try {
            // 连接ftp服务器
         ftp.connect(url, port);
         // 登陆
         ftp.login(userName, passWord);
         // 检验登陆操作的返回码是否正确
         if(!FTPReply.isPositiveCompletion(ftp.getReplyCode())){
            ftp.disconnect();
            return false;
         }

         ftp.enterLocalActiveMode();
         // 设置文件类型为二进制,与ASCII有区别
         ftp.setFileType(FTP.BINARY_FILE_TYPE);
         // 设置编码格式
         ftp.setControlEncoding("GBK");

         // 提取绝对地址的目录以及文件名
         filePath = filePath.replace("ftp://"+url+":"+port+"/", "");
         String dir = filePath.substring(0, filePath.lastIndexOf("/"));
         String file = filePath.substring(filePath.lastIndexOf("/")+1);

         // 进入文件所在目录,注意编码格式,以能够正确识别中文目录
         ftp.changeWorkingDirectory(dir);

         // 检验文件是否存在
         InputStream is = ftp.retrieveFileStream(file);
         if(is == null || ftp.getReplyCode() == FTPReply.FILE_UNAVAILABLE){
            return false;
         }

         if(is != null){
            is.close();
            ftp.completePendingCommand();
         }
         return true;
      } catch (Exception e) {
         e.printStackTrace();
      }finally{
         if(ftp != null){
            try {
               ftp.disconnect();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
      return false;
   }

   /**
    *
    * @param workingDir
    * @param fileName
    * @return
    * @throws IOException
    */
   public Boolean deleteFile(String workingDir, String fileName) {
      boolean result = false;

      try {
         FTPClient ftpClient = new FTPClient();
         ftpClient.connect(url, port);// 连接FTP服务器
         ftpClient.login(userName, passWord);// 登录
         ftpClient.changeWorkingDirectory(workingDir);
         int flag = ftpClient.dele(fileName);
         if (flag == 250) {
            result = true;
         }
      }catch (Exception e){
         e.printStackTrace();
      }
      return result;
   }


   /**
    * 创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
    * @param remote
    * @return
    * @throws IOException
    */
   public boolean createDirecroty(String remote) throws IOException {

      FTPClient ftp = new FTPClient();
      int reply;
      ftp.connect(url, port);
      // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
      ftp.login(userName, passWord);// 登录
      ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
      reply = ftp.getReplyCode();
      if (!FTPReply.isPositiveCompletion(reply)) {
         ftp.disconnect();
      }
      ftp.changeWorkingDirectory("/var/www/html");// 转移到FTP服务器目录

      boolean success = true;
      String directory = remote + "/";
      // String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
      // 如果远程目录不存在,则递归创建远程服务器目录
      if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory), ftp)) {
         int start = 0;
         int end = 0;
         if (directory.startsWith("/")) {
            start = 1;
         } else {
            start = 0;
         }
         end = directory.indexOf("/", start);
         String path = "";
         String paths = "";
         while (true) {
            String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
            path = path + "/" + subDirectory;
            if (!existFile(path, ftp)) {
               if (makeDirectory(subDirectory, ftp)) {
                  changeWorkingDirectory(subDirectory, ftp);
               } else {
                  changeWorkingDirectory(subDirectory, ftp);
               }
            } else {
               changeWorkingDirectory(subDirectory, ftp);
            }
            paths = paths + "/" + subDirectory;
            start = end + 1;
            end = directory.indexOf("/", start);
            // 检查所有目录是否创建完毕
            if (end <= start) {
               break;
            }
         }
      }
      return success;
   }

   /**
    * 改变目录路径
    * @param directory
    * @param ftp
    * @return
    */
   public static boolean changeWorkingDirectory(String directory, FTPClient ftp) {
      boolean flag = true;
      try {
         flag = ftp.changeWorkingDirectory(directory);
         if (flag) {
            //System.out.println("进入文件夹" + directory + " 成功!");
         } else {
            //System.out.println("进入文件夹" + directory + " 失败!");
         }
      } catch (IOException ioe) {
         ioe.printStackTrace();
      }
      return flag;
   }

   /**
    * 创建目录
    * @param dir
    * @param ftp
    * @return
    */
   public static boolean makeDirectory(String dir, FTPClient ftp) {
      boolean flag = true;
      try {
         flag = ftp.makeDirectory(dir);
         if (flag) {
            System.out.println("创建文件夹" + dir + " 成功!");
         } else {
            //System.out.println("创建文件夹" + dir + " 失败!");
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
      return flag;
   }

   /**
    * 判断ftp服务器文件是否存在
    * @param path
    * @param ftp
    * @return
    * @throws IOException
    */
   public static boolean existFile(String path, FTPClient ftp) throws IOException {
      boolean flag = false;
      FTPFile[] ftpFileArr = ftp.listFiles(path);
      if (ftpFileArr.length > 0) {
         flag = true;
      }
      return flag;
   }
}
 类似资料: