1.导入依赖
<!-- FTPClient -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
2.FtpUtil
import lombok.extern.slf4j.Slf4j;
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;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;
@Slf4j
public class FtpUtil {
// ftp服务器地址
private static final String host = "8.134.xxx.xxx";
// ftp服务器端口
private static final int port = 21;
// ftp登录账号
private static final String username = "ftpuser";
// ftp登录密码
private static final String password = "PanGuanQing_xxxx";
// ftp服务器上的相对路径
private static final String remotePath = "/home/ftpuser/image";
/**
* 向ftp服务器上传文件
*
* @param file
* @return
*/
public static String uploadFile(MultipartFile file) {
// 1、创建FTPClient对象
FTPClient ftpClient = new FTPClient();
// 保存FTP控制连接使用的字符集,必须在连接前设置
ftpClient.setControlEncoding("UTF-8");
String remote = null;
try {
// 2、指定服务器地址(端口)
ftpClient.connect(host, port);
// 3、指定账号和密码
ftpClient.login(username, password);
// 连接成功或者失败返回的状态码
int reply = ftpClient.getReplyCode();
// 如果reply返回230表示成功,如果返回530表示无密码或用户名错误或密码错误或用户权限问题。
log.info("ftp连接成功: "+reply);
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return null;
}
// 创建目录
String basePath = "/";
for (String p : remotePath.split("/")) {
basePath += (p + "/");
// 判断目录是否已经存在
boolean hasPath = ftpClient.changeWorkingDirectory(basePath);
if (!hasPath) {
// 创建目录 一次只能创建一个目录
ftpClient.makeDirectory(basePath);
}
}
// 重新指定上传的路径
ftpClient.changeWorkingDirectory(remotePath);
// 6、指定上传方式为二进制方式
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// 得到文件后缀
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
remote = UUIDUtil.uuid().toString() + suffix;
// 7、remote指定上传远程服务器的文件名 local指本地的输入流
ftpClient.storeFile(remote, file.getInputStream());
} catch (SocketException e) {
log.error("文件上传连接错误:" + e.getMessage());
} catch (IOException e) {
log.error("文件上传失败:" + e.getMessage());
} finally {
try {
if (file.getInputStream() != null)
file.getInputStream().close();
ftpClient.logout();
if (ftpClient.isConnected())
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return "http://"+host+"/image/"+remote;
}
/**
* 从ftp服务器下载文件
*
* @param fileName 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @return
*/
public static boolean downloadFile(String fileName, String localPath) {
boolean flag = false;
// 1、创建FTPClient对象
FTPClient ftpClient = new FTPClient();
try {
// 2、指定服务器地址(端口)
ftpClient.connect(host, port);
// 3、指定账号和密码
ftpClient.login(username, password);
// 连接成功或者失败返回的状态码
int reply = ftpClient.getReplyCode();
// 如果reply返回230表示成功,如果返回530表示无密码或用户名错误或密码错误或用户权限问题。
log.info("ftp连接成功: "+reply);
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
log.info("ftp连接失败");
return flag;
}
// 转移到FTP服务器目录
ftpClient.changeWorkingDirectory(remotePath);
FTPFile[] fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + "/" + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftpClient.retrieveFile(ff.getName(), is);
is.close();
}
}
ftpClient.logout();
flag = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
/**
* 删除ftp服务器上的文件
*
* @param filePath ftp服务器保存目录
* @return 成功返回true,否则返回false
*/
public static boolean delFile(String filePath){
boolean flag = false;
// 1、创建FTPClient对象
FTPClient client = new FTPClient();
try {
// 2、指定服务器地址(端口)
client.connect(host, port);
// 3、指定账号和密码
client.login(username, password);
// 连接成功或者失败返回的状态码
int reply = client.getReplyCode();
// 如果reply返回230表示成功,如果返回530表示无密码或用户名错误或密码错误或用户权限问题。
log.info("ftp连接成功: "+reply);
if(!FTPReply.isPositiveCompletion(reply)){
client.disconnect();
log.info("ftp连接失败");
return flag;
}
client.deleteFile(filePath);
client.logout();
flag = true;
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(client.isConnected()){
client.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
}
3.测试
上传文件
/**
* 向ftp服务器上传文件
*
* @param file
* @return
*/
@RequestMapping("/uploadFile")
@ResponseBody
public ResponseResult<String> uploadFile(MultipartFile file){
String upload = FtpUtil.uploadFile(file);
return ResponseResult.createBySuccess(upload);
}
下载文件
/**
* 从ftp服务器下载文件
*
* @param fileName 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @return
*/
@RequestMapping("/downloadFile")
@ResponseBody
public ResponseResult<String> downloadFile(String fileName, String localPath){
boolean b = FtpUtil.downloadFile(fileName, localPath);
return ResponseResult.createBySuccess(b?"文件下载成功":"文件下载失败");
}
删除文件
/**
* 删除ftp服务器上的文件
*
* @param filePath ftp服务器保存目录
* @return
*/
@RequestMapping("/delFile")
@ResponseBody
public ResponseResult<String> delFile(String filePath){
boolean b = FtpUtil.delFile(filePath);
return ResponseResult.createBySuccess(b?"文件删除成功":"文件删除失败");
}