ftp上传图片
package com.daqo.common.utility;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import com.sap.me.frame.BasicBOBeanException;
import com.sap.me.frame.Data;
import sun.misc.BASE64Decoder;
/**
* @author zhihao.sang
* @Description: ftp文件传输工具类
* @date 2020年7月6日 下午1:25:20
*/
public class FtpUtility {
private static FTPClient ftpClient;
static {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("UTF-8");
}
/**
* @Description: 初始化ftp服务器
* @param hostName ftp服务器地址
* @param port ftp服务器端口号默认为21
* @param userName ftp登录账号
* @param password ftp登录密码
* @throws IOException
* @throws BasicBOBeanException
*/
private static void initFtpClient(String hostName, int port, String userName, String password) throws IOException, BasicBOBeanException {
// 连接ftp服务器
ftpClient.connect(hostName, port);
// 登录ftp服务器
ftpClient.login(userName, password);
// 是否成功登录服务器
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
// 20214.simple = 连接文件服务器失败...ftp服务器:%hostName%:%port%
Data data = new Data();
data.put("hostName", hostName);
data.put("port", port);
throw new BasicBOBeanException(20214, data);
}
}
/**
* @Description: 上传文件
* @param hostName ftp服务器地址
* @param port ftp服务器端口号默认为21
* @param userName ftp登录账号
* @param password ftp登录密码
* @param pathname ftp服务保存地址-格式为 "\PITH"要以斜杠开头
* @param fileName 上传到ftp的文件名
* @param inputStream 输入文件流
* @return
* @throws IOException
* @throws BasicBOBeanException
*/
public static boolean uploadFile(String hostName, int port, String userName, String password, String pathname, String fileName, InputStream inputStream) throws IOException, BasicBOBeanException {
boolean uploadSuccess;
try {
// 初始化ftp
initFtpClient(hostName, port, userName, password);
// 设置编码
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// 文件需要保存的路径
createDirectory(pathname);
// 创建文件目录
ftpClient.makeDirectory(pathname);
// 切换到目录
ftpClient.changeWorkingDirectory(pathname);
// 存储文件
uploadSuccess = ftpClient.storeFile(fileName, inputStream);
} finally {
ftpClient.logout();
ftpClient.disconnect();
}
return uploadSuccess;
}
/**
* @Description: 删除文件
* @param hostName ftp服务器地址
* @param port ftp服务器端口号默认为21
* @param userName ftp登录账号
* @param password ftp登录密码
* @param pathname FTP服务器保存目录-格式为 "\PITH"要以斜杠开头
* @param filename 要删除的文件名称
* @return *
* @throws IOException
* @throws BasicBOBeanException
*/
public static boolean deleteFile(String hostName, int port, String userName, String password, String pathname, String filename) throws IOException, BasicBOBeanException {
boolean deleteSuccess = false;
try {
initFtpClient(hostName, port, userName, password);
// 切换FTP目录,并删除
if (ftpClient.changeWorkingDirectory(pathname)) {
deleteSuccess = ftpClient.deleteFile(new String(filename.getBytes("GBK"), StandardCharsets.ISO_8859_1));
}
} finally {
ftpClient.logout();
ftpClient.disconnect();
}
return deleteSuccess;
}
/**
* @Description: 上传图片
* @param hostName ftp服务器地址
* @param port ftp服务器端口号默认为21
* @param userName ftp登录账号
* @param password ftp登录密码
* @param pathname ftp服务保存地址-格式为 "\PITH"要以斜杠开头
* @param fileName 上传到ftp的文件名
* @param imgStr 图片的base64字符串
* @throws IOException
* @throws BasicBOBeanException
*/
public static void uploadImage(String hostName, int port, String userName, String password, String pathname, String fileName, String imgStr) throws IOException, BasicBOBeanException {
// try with resource
try (InputStream inputStream = new ByteArrayInputStream(base64ToByteArray(imgStr))) {
// 初始化客户端
initFtpClient(hostName, port, userName, password);
// 设置文件类型
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// 创建并切换至目录
createDirectory(pathname);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
// 保存文件
ftpClient.storeFile(fileName, inputStream);
} finally {
ftpClient.logout();
ftpClient.disconnect();
}
}
/**
* @Description: base64字符串转换成byte数组
* @param imgStr
* @return
* @throws IOException
*/
private static byte[] base64ToByteArray(String imgStr) throws IOException {
// Base64解码
byte[] b = new BASE64Decoder().decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
// 调整异常数据
b[i] += 256;
}
}
return b;
}
/**
* @Description: 下载图片并转为base64字符串
* @param hostName ftp服务器地址
* @param port ftp服务器端口号默认为21
* @param userName ftp登录账号
* @param password ftp登录密码
* @param pathname FTP服务器文件目录-格式为 "\PITH"要以斜杠开头
* @param filename 文件名称 *
* @return 图片的base64字符串
* @throws IOException
* @throws BasicBOBeanException
*/
public static String downloadImage(String hostName, int port, String userName, String password, String pathname, String filename) throws IOException, BasicBOBeanException {
initFtpClient(hostName, port, userName, password);
InputStream retrieveFileStream = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
// 切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
FTPFile[] ftpFiles = ftpClient.listFiles();
for (FTPFile file : ftpFiles) {
if (filename.equalsIgnoreCase(file.getName())) {
retrieveFileStream = ftpClient.retrieveFileStream(file.getName());
byte[] data = new byte[1024];
int len;
while (-1 != (len = retrieveFileStream.read(data))) {
byteArrayOutputStream.write(data, 0, len);
}
return Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
}
}
} finally {
ftpClient.logout();
ftpClient.disconnect();
if (retrieveFileStream != null) {
retrieveFileStream.close();
}
byteArrayOutputStream.close();
}
return null;
}
/**
* @Description: 创建目录
* @param dir
* @return
* @throws IOException
*/
private static boolean makeDirectory(String dir) throws IOException {
return ftpClient.makeDirectory(dir);
}
/**
* @Description: 创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
* @param remote
* @return
* @throws IOException
*/
private static void createDirectory(String remote) throws IOException {
String directory = remote + "/";
// 如果远程目录不存在,则递归创建远程服务器目录
if (!"/".equalsIgnoreCase(directory) && !changeWorkingDirectory(directory)) {
int start;
int end;
if (directory.startsWith("/")) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf("/", start);
String path = "";
do {
String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), StandardCharsets.ISO_8859_1);
path = path + "/" + subDirectory;
if (!existFile(path)) {
if (!makeDirectory(subDirectory)) {
System.out.println("创建目录[" + subDirectory + "]失败");
}
}
changeWorkingDirectory(subDirectory);
start = end + 1;
end = directory.indexOf("/", start);
// 检查所有目录是否创建完毕
} while (end > start);
}
}
/**
* @Description: 改变目录路径
* @param directory
* @return
* @throws IOException
*/
private static boolean changeWorkingDirectory(String directory) throws IOException {
return ftpClient.changeWorkingDirectory(directory);
}
/**
* @Description: 判断ftp服务器文件是否存在
* @param path
* @return
* @throws IOException
*/
private static boolean existFile(String path) throws IOException {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
if (ftpFileArr.length > 0) {
flag = true;
}
return flag;
}
}