FTPUtil

Ftp Util

@Component
public class FtpUtil {

    private static String FTP_HOST;
    private static int FTP_PORT;
    private static String FTP_USERNAME;
    private static String FTP_PASSWORD;
    private static String FTP_BASE_PATH; //FTP服务器基础目录

    private static String NGINX_HOST;
    private static String NGINX_PORT;

    public static String getFileHttpAddr() {
        return "http://" + NGINX_HOST + ":" + NGINX_PORT;
    }

    private static FTPClient loginFtp() throws IOException {
        FTPClient ftp = new FTPClient();
        int reply;
        ftp.connect(FTP_HOST, FTP_PORT);
        ftp.login(FTP_USERNAME, FTP_PASSWORD);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return null;
        }
        ftp.enterLocalPassiveMode();
        //设置上传文件的类型为二进制类型
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        return ftp;
    }

    /**
     * Description: 向FTP服务器上传文件
     *
     * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
     * @param file     file
     * @return 成功返回 路径
     */
    public static HiddenDocument uploadFile(String filePath, MultipartFile file) {

        FTPClient ftp = null;
        String tempPath = FTP_BASE_PATH;
        try {
            ftp = loginFtp();
            if (ftp == null) return null;
            //切换到上传目录
            if (!ftp.changeWorkingDirectory(FTP_BASE_PATH + filePath)) {
                String[] dirs = filePath.split("/");
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) continue;
                    tempPath += "/" + dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {
                        if (!ftp.makeDirectory(tempPath)) {
                            throw new Exception("创建ftp目录失败");
                        } else {
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            String originalFilename = file.getOriginalFilename();
           // String name = new String(originalFilename.getBytes(), "iso-8859-1");
            String name2=StringUtil.getUUID32()+"."+originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //上传文件
            ftp.storeFile(name2, file.getInputStream());
            ftp.logout();

            HiddenDocument build = HiddenDocument.builder()
                    .docName(originalFilename)
                    .docUri(filePath + "/" + name2)
                    .docType(originalFilename.substring(originalFilename.lastIndexOf(".") + 1))
                    .createTime(new Date())
                    .build();

            return build;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * Description: 从FTP服务器下载文件
     *
     * @param filePath 要下载的文件名
     * @return
     */
    public static InputStream downloadFile(String filePath) {
        FTPClient ftp = null;
        try {
            ftp = loginFtp();
            ftp.changeWorkingDirectory(FTP_BASE_PATH + filePath.substring(0, filePath.lastIndexOf("/") + 1));// 转移到FTP服务器目录
            return ftp.retrieveFileStream(new String(filePath.substring(filePath.lastIndexOf("/") + 1).getBytes(), "iso-8859-1"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return null;
    }

    /**
     * 删除
     *
     * @param filePath
     * @return
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        FTPClient ftp = null;
        try {
            ftp = loginFtp();
            //切换FTP目录
            ftp.changeWorkingDirectory(FTP_BASE_PATH + filePath.substring(0, filePath.lastIndexOf("/") + 1));
            ftp.dele(new String(filePath.substring(filePath.lastIndexOf("/") + 1).getBytes(), "iso-8859-1"));
            ftp.logout();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;

    }

    @Value("${ftp.host}")
    public void setFtpHost(String ftpHost) {
        FTP_HOST = ftpHost;
    }

    @Value("${ftp.port}")
    public void setFtpPort(int ftpPort) {
        FTP_PORT = ftpPort;
    }

    @Value("${ftp.username}")
    public void setFtpUsername(String ftpUsername) {
        FTP_USERNAME = ftpUsername;
    }

    @Value("${ftp.password}")
    public void setFtpPassword(String ftpPassword) {
        FTP_PASSWORD = ftpPassword;
    }

    @Value("${ftp.base-path}")
    public void setFtpBasePath(String ftpBasePath) {
        FTP_BASE_PATH = ftpBasePath;
    }

    @Value("${ftp.host}")
    public  void setNginxHost(String nginxHost) {
        NGINX_HOST = nginxHost;
    }

    @Value("${ftp.nginx-port}")
    public  void setNginxPort(String nginxPort) {
        NGINX_PORT = nginxPort;
    }
}
ftp:
  host:  192.168.0.111
  port: 21
  username: xxxxx
  password: xxxxx
  base-path: "/home/ftpadmin/www/ftp"
  nginx-port: 8080

你可能感兴趣的:(FTPUtil)