1.POM依赖
<!--FTP文件上传-->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
2.FTPUtil
package com.demo.utils;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class FTPUtil {
private final static Logger logger = LoggerFactory.getLogger(FTPUtil.class);
//编码格式
private String LOCAL_CHARSET = "GBK";
//服务器IP
private String ip = "192.168.0.131";
//用户名
private String userName = "root";
//密码
private String passWord = "root";
//保存目录
private String basePath = "/res";
/**
* 初始化FTP服务器
*/
public FTPClient getFtpClient() {
FTPClient ftpClient = new FTPClient();
ftpClient.setControlEncoding("UTF-8");
try {
//设置连接超时时间
ftpClient.setDataTimeout(1000 * 120);
//连接FTP服务器
ftpClient.connect(ip,21);
//登录FTP服务器
ftpClient.login(userName, passWord);
//是否成功登录服务器
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
logger.info("FTP服务器连接失败!");
}
// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK)
if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
"OPTS UTF8", "ON"))) {
LOCAL_CHARSET = "UTF-8";
}
} catch (IOException e) {
logger.info("FTP服务器连接异常!");
}
return ftpClient;
}
/**
* 上传文件
*
* @param targetDir FTP服务保存地址
* @param fileName 上传到FTP的文件名
* @param inputStream 输入文件流
* @return
*/
public boolean uploadFileToFtp(String targetDir, String fileName, InputStream inputStream)throws Exception {
boolean isSuccess = false;
String servicePath = String.format("%s%s%s", basePath, "/", targetDir);
FTPClient ftpClient = getFtpClient();
try {
if (ftpClient.isConnected()) {
//设置上传文件类型为二进制,否则将无法打开文件
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//判断是否目录是否存在
makeDirectory(ftpClient,servicePath);
//设置为被动模式(如上传文件夹成功,不能上传文件,注释这行,否则报错refused:connect )
ftpClient.enterLocalPassiveMode();
//设置被动模式,文件传输端口设置
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
isSuccess = true;
} else {
return isSuccess;
}
} catch (Exception e) {
logger.info(fileName+"上传FTP服务器失败!");
} finally {
if (ftpClient.isConnected()) {
try {
//关闭FTP服务器连接
ftpClient.disconnect();
} catch (IOException e) {
logger.info("FTP服务器关闭异常!");
}
}
}
return isSuccess;
}
/**
* 下载文件 *
*
* @param pathName FTP服务器文件目录 *
* @param targetFileName 下载文件名*
* @param localPath 存储地址*
* @return
*/
public boolean downloadFile(String pathName, String targetFileName, String localPath) {
boolean flag = false;
OutputStream os = null;
FTPClient ftpClient = getFtpClient();
String servicePath = String.format("%s%s%s", basePath, "/", pathName);
try {
System.out.println("开始下载文件");
//切换FTP目录
ftpClient.changeWorkingDirectory(servicePath);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
FTPFile[] ftpFiles = ftpClient.listFiles();
for (FTPFile file : ftpFiles) {
String ftpFileName = file.getName();
if (targetFileName.equalsIgnoreCase(ftpFileName.substring(0, ftpFileName.indexOf(".")))) {
File localFile = new File(localPath);
os = new FileOutputStream(localFile);
ftpClient.retrieveFile(file.getName(), os);
System.out.println("Name:"+file.getName());
os.close();
}
}
ftpClient.logout();
flag = true;
} catch (Exception e) {
e.getMessage();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.getMessage();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.getMessage();
}
}
}
return flag;
}
/**
* 删除文件 *
*
* @param pathName FTP服务器保存目录 *
* @param filename 要删除的文件名称 *
* @return
*/
public boolean deleteFile(String pathName, String filename) {
boolean flag = false;
String servicePath = String.format("%s%s%s", basePath, "/", pathName);
FTPClient ftpClient = getFtpClient();
try {
if (ftpClient.isConnected()) {
//切换FTP目录
// ftpClient.changeWorkingDirectory(servicePath);
ftpClient.enterLocalPassiveMode();
ftpClient.dele(pathName);
ftpClient.removeDirectory("images");
ftpClient.logout();
flag = true;
System.out.println("删除文件成功");
} else {
System.out.println("删除文件失败");
}
} catch (Exception e) {
System.out.println("删除文件失败");
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
return flag;
}
/**
* 创建目录
*
* @param ftpClient FTP服务器
* @param folderPath 文件夹路径
* @return
*/
public void makeDirectory(FTPClient ftpClient, String folderPath) {
try {
//判断是否
boolean flag = ftpClient.changeWorkingDirectory(folderPath);
if (!flag){
//创建文件夹
ftpClient.makeDirectory(folderPath);
//切换文件夹
ftpClient.changeWorkingDirectory(folderPath);
System.out.println("创建文件夹成功!");
}else {
System.out.println("文件夹存在");
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("创建文件夹失败!");
}
}
//判断FTP服务器文件是否存在
public boolean existFile(FTPClient ftpClient, String path) throws IOException {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
if (ftpFileArr.length > 0) {
flag = true;
}
return flag;
}
}