package com.gaotao.modules.ftp.util; import com.gaotao.common.utils.ConfigConstant; import com.gaotao.common.utils.R; import com.gaotao.common.utils.SpringContextUtils; import com.gaotao.modules.oss.cloud.CloudStorageConfig; import com.gaotao.modules.pda.utils.ResponseData; import com.gaotao.modules.sys.service.SysConfigService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; 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.springframework.beans.factory.annotation.Value; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; /** * * @ClassName: FTPUtils * @Description: TODO(这里用一句话描述这个类的作用) * @author lirui * @date 2018年4月29日 * */ @Slf4j public class FTPUtils { private static String serverUrl = "192.168.1.84"; @Value("${com.ftp.ftpPort}") private static int port = 21; private static String username = "ftpadmin"; private static String password = "XJerp123"; private static SysConfigService sysConfigService; private static CloudStorageConfig config; static { sysConfigService = (SysConfigService) SpringContextUtils.getBean("sysConfigService"); //获取储配置信息 config = sysConfigService.getConfigObject(ConfigConstant.FTP_CONFIG_KEY, CloudStorageConfig.class); } /** * @throws IOException * @Title: getFTPClient * @Description: 获取ftp链接 * @author lirui * @date 2018年4月29日 * @param @param serverUrl * @param @param username * @param @param passWord * @param @return 参数 * @return FTPClient 返回类型 * @throws */ public static FTPClient getFTPClient() { FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(config.getFtpHost(), config.getFtpPort()); ftpClient.login(config.getFtpUser(), config.getFtpPassword()); int replay = ftpClient.getReplyCode(); //状态码有误关闭链接 if(!FTPReply.isPositiveCompletion(replay)){ ftpClient.disconnect(); log.info("ftp链接有误,状态码:"+replay); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); } catch (IOException e) { log.info("ftp链接有误,错误信息:"+e.getMessage()); e.printStackTrace(); } return ftpClient; } /** * @throws IOException * * @Title: changeToDir * @Description: 切换工作目录 * @author lirui * @date 2018年4月30日 * @param @return 参数 * @return boolean 返回类型 * @throws */ public static void changeToDir(FTPClient ftpClient,String path) throws IOException{ // 中文转码 path = new String(path.toString().getBytes("GBK"),"iso-8859-1"); /*该部分为逐级创建*/ String[] split = path.split("/"); String newPath = ""; for (String str : split) { if(StringUtils.isBlank(str)) { continue; } newPath = newPath + "/" + str; // 判断是否已有该文件夹 if (!ftpClient.changeWorkingDirectory(newPath)) { boolean makeDirectory = ftpClient.makeDirectory(newPath); System.err.println(str + "创建:" + makeDirectory); } // 切换文件夹 boolean changeWorkingDirectory = ftpClient.changeWorkingDirectory(newPath); System.err.println(";切换:" + changeWorkingDirectory); } } /** * @throws IOException * * @Title: changeToParentDir * @Description: 切换到父级目录 * @author lirui * @date 2018年4月29日 * @param @return 参数 * @return boolean 返回类型 * @throws */ public static void changeToParentDir(FTPClient ftpClient) throws IOException{ ftpClient.changeToParentDirectory(); } /** * * @Title: uploadFile * @Description: 上传文件 * @author lirui * @date 2018年4月29日 * @date 2018年4月30日 * @return 参数 * @return ResponseData 返回类型 * @throws */ public static R uploadFtpFile( File file){ R r = new R(); FTPClient ftpClient = getFTPClient(); //判断链接是否关闭 if(!ftpClient.isConnected()){ log.info("ftp链接出错!链接已关闭!"); r.error(300,"ftp链接出错!链接已关闭!"); return r; } //上传操作 FileInputStream fis = null; try { fis = new FileInputStream(file); ftpClient.setBufferSize(10000); //切换目录 ftpClient.setControlEncoding("UTF-8"); changeToDir(ftpClient, config.getFtpDir()); boolean flag = ftpClient.storeFile(new String(file.getName().getBytes("gbk"), "iso-8859-1"), fis); if(!flag){ log.info("ftp上传失败!"); r.error(303,"ftp上传失败!"); return r; } ftpClient.logout(); r.ok("ftp上传成功!"); r.put("url",config.getFtpDir()+"//"+file.getName()); return r; } catch (FileNotFoundException e) { log.info("ftp上传出错!错误信息:"+e.getMessage()); r.error(301,"ftp上传出错!错误信息:"+e.getMessage()); e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { fis.close(); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } return r; } /** * * @Title: getFtpFile * @Description: 下载文件 * @author lirui * @date 2018年4月30日 * @param serverUrl ftp路径 * @param username 用户名 * @param password 密码 * @param path 当前目录 * @param fileName 当前目录下下载的文件名称 * @return 参数 * @return File 返回类型 * @throws */ public static ResponseData downFtpFile(String serverUrl,String username,String password,String path,String fileName){ ResponseData responseData = new ResponseData(); FTPClient ftpClient = getFTPClient(); //判断链接是否关闭 if(!ftpClient.isConnected()){ log.info("ftp链接出错!链接已关闭!"); responseData.setCode("300"); responseData.setMsg("链接出错!"); return responseData; } //进入工作空间 boolean flag = true; FileOutputStream fos = null; try { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); flag = ftpClient.changeWorkingDirectory("/"); if(!flag){ log.info("ftp链接出错!文件夹不存在!"); responseData.setCode("300"); responseData.setMsg("ftp链接出错!文件件不存在!"); return responseData; } //获取当前目录下的所有文件名称 ftpClient.sendCommand("OPTS UTF8 ON"); FTPFile[] ftpFiles = ftpClient.listFiles(); //文件存在是否存在的标记 boolean isExist = false; //循环判断文件 for(int i = 0; i0){ //把文件流写到缓冲区里 toClient.write(buffer,0,length); } toClient.write(buffer); toClient.flush(); fis.close(); toClient.close(); log.info("文件下载完成!文件名称:"+fileName); break; } } ftpClient.completePendingCommand(); if(isExist){ r.put("msg" ,"ftp下载成功!"); r.put("success", true); }else{ r.put("msg" ,"ftp下载失败!"); r.put("success", false); } } catch (IOException e) { log.info("ftp下载出错!错误信息:"+e.getMessage()); // TODO Auto-generated catch block e.printStackTrace(); }finally { //关闭流和链接 try { // if(fos!=null){ // fos.close(); // } if(ftpClient!=null){ ftpClient.logout(); } } catch (IOException e) { log.info("关闭流和链接出错!错误信息:"+e.getMessage()); e.printStackTrace(); } } return r; } /**` * @Desc ftp文件下载 * @param response * @param path * @param fileName */ public static void downFile( HttpServletResponse response, String path, String fileName){ FTPClient ftpClient = getFTPClient(); //判断链接是否关闭 if(!ftpClient.isConnected()){ log.info("ftp链接出错!链接已关闭!"); } //进入工作空间 boolean flag = true; try { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); if(path == null || "".equals(path)){ path = "/"; } String name=new String(path.getBytes("UTF-8"),"iso-8859-1"); flag = ftpClient.changeWorkingDirectory(name); if(!flag){ log.info("ftp链接出错!文件夹不存在!"); } //获取当前目录下的所有文件名称 ftpClient.sendCommand("OPTS UTF8 ON"); FTPFile[] ftpFiles = ftpClient.listFiles(); //文件存在是否存在的标记 boolean isExist = false; //循环判断文件 for(int i = 0; i0){ //把文件流写到缓冲区里 toClient.write(buffer,0,length); } toClient.write(buffer); toClient.flush(); fis.close(); toClient.close(); ftpClient.completePendingCommand(); log.info("下载完成!文件名称:"+fileName); } } ftpClient.completePendingCommand(); if(isExist){ log.info("下载完成!文件名称:"+fileName); }else{ log.info("下载失败!文件名称:"+fileName); } } catch (IOException e) { log.info("ftp下载出错!错误信息:"+e.getMessage()); // TODO Auto-generated catch block e.printStackTrace(); }finally { //关闭流和链接 try { if(ftpClient!=null){ ftpClient.logout(); } } catch (IOException e) { log.info("关闭流和链接出错!错误信息:"+e.getMessage()); // TODO Auto-generated catch block e.printStackTrace(); } } } // 本地盘直接读取 public static void downFile1(String path, String fileName){ String ipPath = config.getFtpDir()+fileName; File file = new File(ipPath); try { OutputStream os = new FileOutputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } } }