引包
import com.syoa.mapper.FtpserverMapper;
import com.syoa.model.AppUser;
import com.syoa.model.Ftpserver;
import com.syoa.service.FtpServerService;
import com.syoa.utils.Base64StrToImage;
import com.syoa.utils.Ret;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
正文
public Ret uploadFile(Ftpserver ftpserver1, String tempID, AppUser user,String base64) {
MultipartFile file =Base64StrToImage.base64Mutipartpdf(base64);//这个就是字符串转Multip..文件的API
/* List list = ftpserverMapper.select(ftpserver);
if (list.size() != 1) {
log.error("错误当前ftp有效地址不止一个");
return Ret.fail("msg", "当前文件存储的有效地址不止一个");
}
Ftpserver ftp = list.get(0);*/
String today=new SimpleDateFormat("yyyyMMdd").format(new Date());
//TODO 这个对象以后从数据库读
//TODO 这个对象以后从数据库读
Ftpserver ftpserver = new Ftpserver();
ftpserver.setHost("192.168.31.252");
ftpserver.setPassword("1");
ftpserver.setUsername("syftp");
ftpserver.setPort(21);
String path_wl=today+"\\"+tempID;
String name="合同.pdf";
ftpserver.setEncoding("utf-8");
FTPClient ftp = new FTPClient();
try {
//设置编码
ftp.setControlEncoding(ftpserver.getEncoding());
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
//连接ftp服务器
ftp.connect(ftpserver.getHost(),ftpserver.getPort());
//响应码
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
ftp.disconnect();
}
//登录ftp
boolean login = ftp.login(ftpserver.getUsername(), ftpserver.getPassword());
if(!login){
return Ret.fail("msg","ftp服务器登录失败。请重新开始");
}
//设置为二进制格式
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
List<String> listpath = getPathList(path_wl);
//循环遍历创建路径
System.out.println("已连接"+ftp.isConnected());//查看ftp是否已连接
if(!ftp.changeWorkingDirectory(path_wl)){
boolean b = ftp.makeDirectory(path_wl);
if(b){
ftp.changeWorkingDirectory(path_wl);
ftp.appendFile(name,file.getInputStream());
}
}else{
ftp.appendFile(name,file.getInputStream());
}
System.err.println("写入成功==========");
//return Ret.ok("msg",subDir);
} catch (IOException e) {
log.error("文件保存失败:"+e.getMessage());
e.printStackTrace();
return Ret.fail("msg","文件保存失败"+e.getMessage());
}finally {
try {
ftp.logout();
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return Ret.ok("msg","文件保存成功");
}
工具类分解路径
/**
* @Author Mr伍
* @Description //TODO 获取每一级路径
* @Date 2020/1/8
* @Param [path]
* @return java.util.List
**/
private List<String> getPathList(String path){
String[] dirs = path.split("/");
List<String> list = new ArrayList<>();
String pathname = "";
for(String str : dirs){
if(StringUtils.isEmpty(str)){
continue;
}
pathname = pathname + "/" + str;
list.add(pathname);
}
return list;
}
//关闭ftp
public static void close(FTPClient ftp){
try {
if(ftp.isConnected()){
ftp.logout();
ftp.disconnect();
}
ftp = null;
} catch (Exception e) {
e.printStackTrace();
}
}
只创建ftp的路径文件夹
private boolean createDir(String host,int port,String userName,String password,String path){
/* String host = "127.0.0.0";
int port = 21;
String userName = "test";
String password = "123456";
String path = "/work/project/test/down/content";*/
//分割路径
List<String> list = getPathList(path);
try {
FTPClient ftp = new FTPClient();
//基本设置
ftp.setDefaultTimeout(20000);
ftp.setDataTimeout(3600000);
ftp.setConnectTimeout(60000);
ftp.connect(host, port);
ftp.login(userName, password);
ftp.setBufferSize(4096);
ftp.setKeepAlive(true);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
//循环遍历创建路径
for(int i=0; i<list.size(); i++){
if(!ftp.changeWorkingDirectory(list.get(i))){//若路径未存在则创建路径
if(!ftp.makeDirectory(list.get(i))){//若路径创建失败则不再继续处理
System.out.println("create dir fail --> " + list.get(i));
close(ftp);
return false;
}
}
}
System.out.println(ftp.isConnected());//查看ftp是否已连接
System.out.println(ftp.changeWorkingDirectory(path));//查看目录是否已存在
close(ftp);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
package com.syoa.utils;
import java.io.*;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.PrintCommandListener;
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.web.multipart.MultipartFile;
public class FtpUtil {
private final static Log logger = LogFactory.getLog(FtpUtil.class);
private static String LOCAL_CHARSET = "UTF-8";
// FTP协议里面,规定文件名编码为iso-8859-1
private static String SERVER_CHARSET = "ISO-8859-1";
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static Date TODAY_TIME = new Date();
/**
* @return
* @Author Mr伍
* @Description //TODO
* @Date 2020/4/1
* @Param
**/
public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient = new FTPClient();
ftpClient.connect(ftpHost, ftpPort); // 连接FTP服务器
ftpClient.login(ftpUserName, ftpPassword); // 登陆FTP服务器
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
logger.info("未连接到FTP,用户名或密码错误。");
ftpClient.disconnect();
} else {
logger.info("FTP连接成功。");
}
} catch (SocketException e) {
e.printStackTrace();
logger.info("FTP的IP地址可能错误,请正确配置。");
} catch (IOException e) {
e.printStackTrace();
logger.info("FTP的端口错误,请正确配置。");
}
return ftpClient;
}
//判断ftp的目标文件下是否有此文件
public static boolean isExsits(String ftpPath, String fileName, FTPClient ftpx) {
try {
FTPFile[] files = ftpx.listFiles(ftpPath);
if (files != null && files.length > 0) {
System.out.println("files size:" + files[0].getSize());
for (FTPFile file : files
) {
String st = new String(file.getName().getBytes(LOCAL_CHARSET), SERVER_CHARSET);
String st1 = new String(st.getBytes(SERVER_CHARSET), LOCAL_CHARSET);
if (st1.equals(fileName)) {
return true;
}
}
return false;
} else {
return false;
}
} catch (Exception e) {
logger.error("获取文件列表失败" + e.getMessage() + e.getClass().getName());
return false;
//e.printStackTrace();
}
}
/*
* 从FTP服务器下载文件
* @param ftpHost FTP IP地址
* @param ftpUserName FTP 用户名
* @param ftpPassword FTP用户名密码
* @param ftpPort FTP端口
* @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa
* @param localPath 下载到本地的位置 格式:H:/download
* @param fileName FTP服务器上要下载的文件名称
* @param targetFileName 本地上要的文件名称
*/
public static String downloadFtpFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String localPath, String fileName, String targetFileName) {
FTPClient ftpClient = null;
try {
ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
"OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
LOCAL_CHARSET = "UTF-8";
}
if(!ftpClient.changeWorkingDirectory(ftpPath)){
return "文件夹路径不对";
};
boolean flag = isExsits(ftpPath, fileName, ftpClient);
if (!flag) {
return "文件:" + fileName + " 不存在";
}
String f_ame = new String(fileName.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING); //编码文件格式,解决中文文件名
File localFile = new File(localPath + File.separatorChar + targetFileName);
OutputStream os = new FileOutputStream(localFile);
ftpClient.retrieveFile(f_ame, os);
os.close();
ftpClient.logout();
return "下载成功";
} catch (FileNotFoundException e) {
logger.error("没有找到" + ftpPath + "文件");
e.printStackTrace();
} catch (SocketException e) {
logger.error("连接FTP失败.");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
logger.error("文件读取错误。");
e.printStackTrace();
}
return "下载失败";
}
public static String uploadFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String base64, String fileName) {
String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
String path_wl =today;
MultipartFile file = Base64StrToImage.base64MutipartFile(base64);
String name = fileName;
System.err.println(name);
FTPClient ftp = new FTPClient();
try {
//设置编码
ftp.setControlEncoding("utf-8");
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
//连接ftp服务器
ftp.connect(ftpHost, ftpPort);
//响应码
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
ftp.disconnect();
}
//登录ftp
boolean login = ftp.login(ftpUserName, ftpPassword);
if (!login) {
return "ftp服务器登录失败。请重新开始";
}
//设置为二进制格式
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
// System.out.println("已连接"+ftp.isConnected());//查看ftp是否已连接
logger.debug("ftp连接状态" + ftp.isConnected());
if (!ftp.changeWorkingDirectory(path_wl)) {
boolean b = ftp.makeDirectory(path_wl);
if (b) {
ftp.changeWorkingDirectory(path_wl);
ftp.appendFile(name, file.getInputStream());
}
} else {
ftp.appendFile(name, file.getInputStream());
}
logger.debug("写入成功==========");
} catch (IOException e) {
logger.error("文件保存失败:" + e.getMessage());
e.printStackTrace();
return "文件保存失败";
} finally {
try {
ftp.logout();
ftp.disconnect();
if (ftp.isConnected()) {
ftp.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "文件保存成功";
}
public static void main(String[] args) {
String ftpHost = "localhost";
String ftpUserName = "syftp";
String ftpPassword = "1";
int ftpPort = 21;
String ftpPath = "\\201994\\";
String fileName = "中文123.jpeg";
//上传一个文件
try {
File f = new File("E:\\" + "身份证.jpeg");
String str=ImageKit.encodeBase64(f);
str="data:image/jpeg;base64,"+str;
String flag = FtpUtil.uploadFile(ftpHost, ftpUserName, ftpPassword, ftpPort,str,fileName);
System.err.println(flag);
String tmpPath = System.getProperty("java.io.tmpdir");
System.out.println(tmpPath);//本机临时文件夹 C:\Users\DELL\AppData\Local\Temp\
//文件下载
// String resoult = FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, "E:\\", fileName, "身份证.jpeg");
//System.err.println(resoult);
System.err.println("成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
/**
* 根据名称获取文件,以字节数组返回
*
* @param ftpPath FTP服务器文件相对路径,例如:test/123
* @param fileName 文件名,例如:test.xls
* @return byte[] 字节数组对象
*/
public static byte[] getFileBytesByName(String ftpPath, String fileName, String ftpHost, String ftpUserName, String ftpPassword, int ftpPort) {
// 登录
FTPClient ftpClient = null;
//创建byte数组输出流
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
try {
//获取FTPClient
ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
ftpClient.changeWorkingDirectory(ftpPath);
boolean flag= isExsits(ftpPath,fileName,ftpClient);
if(!flag){
//文件不存在
logger.error("文件不存在");
return byteStream.toByteArray();
}
//创建文件夹
ftpClient.makeDirectory("summer");
// 设置被动模式,开通一个端口来传输数据
ftpClient.enterLocalPassiveMode();
String[] fs = ftpClient.listNames();
// 判断该目录下是否有文件
if (fs == null || fs.length == 0) {
logger.error(ftpPath + "该目录下没有文件");
return byteStream.toByteArray();
}
for (String ff : fs) {
String ftpName = ff;
if (ftpName.equals(fileName)) {
try (InputStream is = ftpClient.retrieveFileStream(ff);) {
byte[] buffer = new byte[1024 * 1024 * 4];
int len = -1;
while ((len = is.read(buffer, 0, 1024 * 1024 * 4)) != -1) {
byteStream.write(buffer, 0, len);
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return byteStream.toByteArray();
}
}