package com.xwtech.commons.util.file;import java.io.*;import java.net.SocketException;import com.xwtech.commons.config.FTPConfig;import com.xwtech.commons.config.ProjectConfig;import com.xwtech.commons.constant.Constants;import org.apache.commons.io.IOUtils;import org.apache.commons.net.ftp.FTP;import org.apache.commons.net.ftp.FTPClient;import org.apache.commons.net.ftp.FTPReply;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/*** @ClassName: FTPFileUtils* @Description: FTP文件上传 工具类* @author xilongfei* @date 2020年2月26日下午7:16:35*/public class FTPFileUtils {private static final Logger logger = LoggerFactory.getLogger(FTPFileUtils.class);/*** 设置缓冲区大小2M**/private static final int BUFFER_SIZE = 1024 * 1024 * 2;/*** FTPClient对象**/private static FTPClient ftpClient = null;/*** @Title: FTPUploadFile* @Description: (方法描述)* @author xilongfei* @date 2020年2月26日下午7:19:30// * @param ftp_IP* @param path FTP服务器保存目录* @param filename 上传到FTP服务器上的文件名* @param file 文件* @return boolean 成功/失败*/public static boolean FTPUploadFile(String path, String filename, File file) {if(file == null ) return false;FTPClient ftp = new FTPClient();InputStream input = null;try {logger.info(FTPConfig.getFtpIp());// 连接FTP服务器。如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器ftp.connect(FTPConfig.getFtpIp(), FTPConfig.getFtpPost());//账号登录if(!ftp.login(FTPConfig.getFtpUserName(), FTPConfig.getFtpPassWord())){//登录失败logger.error("FTP服务登录失败");closeCon(ftp);return false;}int reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {closeCon(ftp);return false;}ftp.enterLocalPassiveMode();ftp.setFileType(FTP.BINARY_FILE_TYPE);//判断上传路径是否存在if(!isDirExist(ftp,path)){//创建上传路径if(!createDir(path,ftp)){closeCon(ftp);return false;}}//切换到指定路径ftp.changeWorkingDirectory(path);//转换为文件流input = new FileInputStream(file);//上传文件ftp.storeFile(filename, input);input.close();logger.info(FTPConfig.getFtpIp()+"FTP上传成功");return true;} catch (Exception e) {logger.error(FTPConfig.getFtpIp()+"FTP上传失败:"+e.getMessage(), e);return false;}finally {IOUtils.closeQuietly(input);//关闭连接closeCon(ftp);}}/*** @Description: 判断Ftp目录是否存在* @return boolean*/public static boolean isDirExist(FTPClient ftpClient, String dir) {try {if(ftpClient.cwd(dir)==550) return false;} catch (IOException e1) {return false;}return true;}/*** 创建目录(有则切换目录,没有则创建目录)** @param dir 文件目录* @param ftp* @return boolean*/public static boolean createDir(String dir, FTPClient ftp){//目录为空, 不做处理 返回成功if(StringUtils.isEmpty(dir)) return true;String path;try {//目录编码,解决中文路径问题path = new String(dir.toString().getBytes("GBK"),"iso-8859-1");//尝试切入目录if(ftp.changeWorkingDirectory(path)) return true;//删除起始与末尾字符 "/"dir = StringUtils.trimStart(dir, "/");dir = StringUtils.trimEnd(dir, "/");String[] arr = dir.split("/");StringBuffer sbfDir=new StringBuffer();//循环生成子目录for(String s : arr){sbfDir.append("/");sbfDir.append(s);//目录编码,解决中文路径问题path = new String(sbfDir.toString().getBytes("GBK"),"iso-8859-1");//尝试切入目录if(ftp.changeWorkingDirectory(path)) continue;if(!ftp.makeDirectory(path)){System.out.println("[失败]ftp创建目录:"+sbfDir.toString());return false;}System.out.println("[成功]创建ftp目录:"+sbfDir.toString());}//将目录切换至指定路径return ftp.changeWorkingDirectory(path);} catch (Exception e) {logger.error("FTP创建上传目录失败:"+e.getMessage(), e);return false;}}/*** @功能描述:ftp删除文件* @param filePath 文件路径 格式: home/webapp/// * @param filename 文件名称 格式: weijian.jpg*/public static boolean deleteFile(String filePath){FTPClient ftp = new FTPClient();try {// 连接FTP服务器。如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器ftp.connect(FTPConfig.getFtpIp(), FTPConfig.getFtpPost());//账号登录if(!ftp.login(FTPConfig.getFtpUserName(), FTPConfig.getFtpPassWord())){//登录失败closeCon(ftp);return false;}int reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {closeCon(ftp);return false;}ftp.dele(filePath);System.out.println(FTPConfig.getFtpIp()+"服务器下"+ filePath +"文件删除成功");return true;} catch (IOException e) {logger.error("删除FTP上文件异常:"+e.getMessage(), e);closeCon(ftp);}finally{closeCon(ftp);}return false;}/*** 销毁ftp连接* @param ftpClient*/public static void closeCon(FTPClient ftpClient){if(ftpClient !=null){if(ftpClient.isConnected()){try {ftpClient.logout();ftpClient.disconnect();} catch (IOException e) {logger.error(FTPConfig.getFtpIp()+"FTP链接销毁失败:"+e.getMessage(), e);}}}}/*** 连接FTP服务器** @param address 地址,如:127.0.0.1* @param port 端口,如:21* @param username 用户名,如:root* @param password 密码,如:root*/private static void login(String address, int port, String username, String password) {ftpClient = new FTPClient();try {ftpClient.connect(address, port);ftpClient.login(username, password);ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//限制缓冲区大小ftpClient.setBufferSize(BUFFER_SIZE);ftpClient.enterLocalPassiveMode();if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {logger.info("未连接到FTP,用户名或密码错误。");closeCon(ftpClient);}} catch (Exception e) {logger.error("FTP登录失败:"+e.getMessage(), e);}}/*** @Title: downloadFtpFile* @Description: 从FTP服务器下载文件* @author xilongfei* @date 2020年7月3日下午12:08:42* @param ftpPath FTP 服务器中文件所在路径 格式:/ftptest/aa* @param fileName FTP 服务器上要下载的文件名称* @param localPath 下载到本地的位置-自定义路径 格式:ftptest/download ; 整体: 公共路径+ftptest/download* @return String 本地访问路径*/public static String downloadFtpFile( String ftpPath, String localPath, String fileName) throws Exception{if(StringUtils.isEmpty(ftpPath) || StringUtils.isEmpty(localPath) || StringUtils.isEmpty(fileName)) {return null;}try{//创建本地路径boolean bo = getAbsoluteFile(ProjectConfig.getProfile()+localPath);if(!bo) {throw new IOException("创建本地存放路径失败");}bo = downloadFtpFile(FTPConfig.getFtpIp(), FTPConfig.getFtpPost(), FTPConfig.getFtpUserName(),FTPConfig.getFtpPassWord(), ftpPath, ProjectConfig.getProfile()+localPath, fileName);if(!bo) {throw new IOException("下载ftp指定文件失败");}//本地访问路径return Constants.RESOURCE_PREFIX + localPath + fileName;}catch (Exception e){e.printStackTrace();}return "";}/*** 从FTP服务器下载文件* @param ftpHost FTP IP地址* @param ftpPort FTP 端口* @param ftpPassword FTP 用户名密码* @param ftpUserName FTP 用户名* @param ftpPath FTP 服务器中文件所在路径 格式:/ftptest/aa* @param fileName FTP 服务器上要下载的文件名称* @param localPath 下载到本地的位置 格式:H:/download 或 ftptest/aa(linux系统)*/public static boolean downloadFtpFile(String ftpHost, int ftpPort, String ftpPassword,String ftpUserName,String ftpPath, String localPath, String fileName) {boolean b = false;try {// 登录login(ftpHost, ftpPort,ftpPassword,ftpUserName );ftpClient.changeWorkingDirectory(ftpPath);String f_ame = new String(fileName.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING); //编码文件格式,解决中文文件名//本地图片存储路径File localFile = new File(localPath + File.separatorChar + fileName);OutputStream os = new FileOutputStream(localFile);ftpClient.retrieveFile(f_ame, os);b = true;} catch (FileNotFoundException e) {System.out.println("没有找到" + ftpPath + "文件");e.printStackTrace();} catch (SocketException e) {System.out.println("连接FTP失败。");e.printStackTrace();} catch (IOException e) {System.out.println("文件读取错误。");e.printStackTrace();} finally{closeCon(ftpClient);}return b;}/*** @Title: getAbsoluteFile* @Description: 创建文件路径-本地* @author xilongfei* @date 2020年7月3日下午12:12:07* @param uploadDir* @return boolean*/private static final boolean getAbsoluteFile(String uploadDir){boolean bo = true;File desc = new File(uploadDir);if(desc.exists()) {System.out.println("目录已存在");return true;}//创建路径desc.mkdirs();System.out.println("创建目录"+ uploadDir + "成功");return bo;}}
配置:
package com.xwtech.commons.config;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;/*** @ClassName: FTPConfig* @Description: FTP 相关配置* @author xilongfei* @date 2020年2月26日下午7:40:57*/@Component@ConfigurationProperties(prefix = "ftp")public class FTPConfig{/** FTP链接IP地址 */private static String ftpIp;/** ftp登录账号 */private static String ftpUserName;/** ftp登录密码 */private static String ftpPassWord;/** ftp链接端口 */private static Integer ftpPost;/** ftp公共上传路径 */private static String ftpPath;/** 外部访问路径-数据库存储路径 */private static String httpPath;public static String getFtpIp() {return ftpIp;}public void setFtpIp(String ftpIp) {FTPConfig.ftpIp = ftpIp;}public static String getFtpUserName() {return ftpUserName;}public void setFtpUserName(String ftpUserName) {FTPConfig.ftpUserName = ftpUserName;}public static String getFtpPassWord() {return ftpPassWord;}public void setFtpPassWord(String ftpPassWord) {FTPConfig.ftpPassWord = ftpPassWord;}public static Integer getFtpPost() {return ftpPost;}public void setFtpPost(Integer ftpPost) {FTPConfig.ftpPost = ftpPost;}public static String getFtpPath() {return ftpPath;}public void setFtpPath(String ftpPath) {FTPConfig.ftpPath = ftpPath;}public static String getHttpPath() {return httpPath;}public void setHttpPath(String httpPath) {FTPConfig.httpPath = httpPath;}}
application.yml文件:
# FTP相关配置ftp:#FTP链接IPftpIp: 192.168.0.225#ftp用户名ftpUserName: 'webapp'#ftp密码ftpPassWord: 'Tec110_xw'#ftp端口ftpPost: 21#ftp公共上传路径ftpPath: /home/webapp/ieguard/webdata/manage_resource#访问路径-数据库存储路径httpPath : http://hb.tztec.com:9999/app/manageres#httpPath : https://192.168.0.218:11000/app/manageres
文章转载自元素周期表A,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




