ftputil 下载图片工具类
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
public class FtpUtils { private static final Logger logger = LoggerFactory.getLogger(FtpUtils.class); private static FTPClient ftpClient; /** *@Description ftp登录 *@Param [ftpHost, ftpUserName, ftpPassword, ftpPort] *@return org.apache.commons.net.ftp.FTPClient **/ public static FTPClient getFTPCLient(String ftpHost,String ftpUserName,String ftpPassword,int ftpPort){ try{ ftpClient = new FTPClient(); //连接FTP服务器 ftpClient.connect(ftpHost,ftpPort); //登录FTP服务器 ftpClient.login(ftpUserName,ftpPassword); //设置编码格式(支持中文) // ftpClient.setControlEncoding("UTF-8"); //设置传输格式为二进制 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){ logger.error("未连接到FTP,用户名或密码错误"); ftpClient.disconnect(); }else{ logger.info("FTP连接成功"); } }catch(Exception e){ logger.error(HikLog.toLog("ftp connect error",e); } return ftpClient; } /** *@Description 判断ftp是否连接成功 *@Param [] *@return boolean **/ public static boolean isConnect(){ if (ftpClient!=null && ftpClient.isConnected()){ return FTPReply.isPositiveCompletion(ftpClient.getReplyCode()); }else{ logger.info("ftp连接断开"); return false; } } /** *@Description 关闭ftp连接 *@Param [] *@return void **/ public static void close(){ if (ftpClient!=null && ftpClient.isConnected()){ try{ ftpClient.logout(); ftpClient.disconnect(); }catch(Exception e){ logger.error("ftp close error",e); } } } /** *@Description 检查文件是否存在 *@Param [ftpPath] *@return boolean **/ public static boolean isFileExist(String ftpPath){ boolean result = true; try{ ftpClient.listFiles(ftpPath); }catch(Exception e){ result = false; logger.error("check file error",e); } return result; } /** *@Description 从ftp上下载图片 *@Param [filePath, fileName] *@return java.lang.String **/ public static String downloadPic(String filePath,String fileName) { InputStream is = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] data = null; String picBASE64 = ""; if (isFileExist(filePath)){ try{ ftpClient.changeToParentDirectory(); ftpClient.changeWorkingDirectory(filePath); is = ftpClient.retrieveFileStream(fileName);
// 程序运行在windows操作系统,下载的文件名称有中文时,可以用下面的两行代码 // ftpClient.changeWorkingDirectory(new String(filePath.getBytes("UTF-8"),"iso-8859-1")); // is = ftpClient.retrieveFileStream(new String(fileName.getBytes("UTF-8"),"iso-8859-1")); byte[] buffer = new byte[1024]; int n = 0; if (is!=null){ while(-1 != (n = is.read(buffer))){ baos.write(buffer,0,n); } data = baos.toByteArray(); BASE64Encoder encoder = new BASE64Encoder(); picBASE64 = encoder.encode(data); is.close(); }else{ logger.error("ftp获取文件流失败",e); } }catch(Exception e){ logger.error("download error",e); } } return picBASE64; } }