Maven依赖引用:
<!-- httpclient begin -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!-- ftp begin -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.9.RELEASE</version>
<scope>compile</scope>
</dependency>
=================================================================================================
package com.common.util;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @Description ftp文件上传工具类
* @Author FangYN
* @Date 2019/12/25
**/
public class FtpFileUtil {
public static void main(String[] args) throws IOException {
String host = "127.0.0.1";
int port = 30;// 所在服务器FTP的端口(默认21,可配置)
String username = "admin";
String password = "admin";
String savePath = "/uploads/";
String filePath = "image";
String newFileName = UUIDUtils.getUUID()+".jpg";
System.out.println("文件名:"+newFileName);
File pdfFile = new File("C:\\Users\\ww\\Pictures\\Saved Pictures\\1111.jpg");
FileInputStream fileInputStream = new FileInputStream(pdfFile);
MultipartFile multipartFile = new MockMultipartFile(pdfFile.getName(), pdfFile.getName(),
ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
Boolean resultBoolean = FtpFileUtil.uploadFile(host, port, username, password, savePath, filePath, newFileName, multipartFile.getInputStream());
System.out.println(resultBoolean);
// System.out.println("访问地址:http://"+host+":90/uploads"+savePath+"/"+filePath+"/"+newFileName);
}
/**
* 上传文件
* @param host ftp的ip
* @param port ftp的端口
* @param username
* @param password
* @param projectPath 保存路径的路径(以项目名为主)
* @param filePath 文件夹名称
* @param fileName 保存的文件名
* @param inputStream 文件流
* @return
* @throws IOException
*/
public static Boolean uploadFile(String host, int port, String username, String password,
String projectPath, String filePath, String fileName, InputStream inputStream) throws IOException {
//1、创建FTPClient对象(对于连接ftp服务器,以及上传和上传都必须要用到一个对象)
FTPClient ftp = getConnect(host, port, username, password);
if (ftp == null) return false;
try{
// 2、changWorkingDirectory(linux上的文件夹):检测所传入的目录是否存在,如果存在返回true,否则返回false
// basePath+filePath-->/uploads/601159
String path = projectPath+filePath;
if(!ftp.changeWorkingDirectory(path)) createDir(path, ftp);
// 3.把文件转换为二进制字符流的形式进行上传
ftp.setFileType(FTP.BINARY_FILE_TYPE);
// 4、这才是真正上传方法storeFile(filename,input),返回Boolean雷类型,上传成功返回true
if (!ftp.storeFile(fileName, inputStream)) return false;
// 5.关闭输入流
inputStream.close();
// 6.退出ftp
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
throw new IOException(e);
} finally {
closeFtp(ftp);
}
return true;
}
/**
* 重命名/移动 文件
* @param host
* @param port
* @param username
* @param password
* @param oldPath 原有文件路径及文件名
* @param projectPath 项目名路径
* @param newPath 文件新路径 不含文件名 文件夹不变动时,传null值 移动文件时必传
* @param newFileName 新的文件名字,必传
* @return
* @throws IOException
*/
public static Boolean renameFile(String host, int port, String username, String password,
String oldPath, String projectPath, String newPath, String newFileName) throws IOException {
//1、创建FTPClient对象(对于连接ftp服务器,以及上传和上传都必须要用到一个对象)
FTPClient ftp = getConnect(host, port, username, password);
if (ftp == null || StringUtils.isEmpty(oldPath)) return false;
String path = "";
try{
// 2.判断文件名是否修改 思路:先根据旧的文件路径更改文件名后,再判断修改路径
String oldFileName = oldPath.substring(oldPath.lastIndexOf(File.separator)+1);
if (!oldFileName.equals(newFileName)) {// 更改文件名
path = oldPath.substring(0, oldPath.lastIndexOf(File.separator));
ftp.changeWorkingDirectory(path);//将目录切换至指定路径
path = path+"/"+newFileName;
ftp.rename(oldPath, path);
}
// 3.判断修改保存的文件夹--即移动文件
if (!StringUtils.isEmpty(newPath)) {// 更改路径
if (StringUtils.isEmpty(path)) path = oldPath;
ftp.enterLocalPassiveMode();
ftp.setFileType(FTP.BINARY_FILE_TYPE);
InputStream inputStream = ftp.retrieveFileStream(new String(path.getBytes("UTF-8"), "ISO-8859-1"));
uploadFile(host, port, username, password, projectPath, newPath, newFileName, inputStream);
ftp.deleteFile(path);
}
// 4.退出ftp
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
throw new IOException(e);
} finally {
closeFtp(ftp);
}
return true;
}
/**
* 请求连接Ftp
* @param host
* @param port
* @param username
* @param password
* @return
* @throws IOException
*/
private static FTPClient getConnect(String host, int port, String username, String password) throws IOException {
FTPClient ftp = new FTPClient();
//1、定义返回的状态码
int reply;
try {
//2、连接ftp(当前项目所部署的服务器和ftp服务器之间可以相互通讯,表示连接成功)
ftp.connect(host, port);
//3、输入账号和密码进行登录
ftp.login(username, password);
//4、接受状态码(如果成功,返回230,如果失败返回503)
reply=ftp.getReplyCode();
//5、根据状态码检测ftp的连接,调用isPositiveCompletion(reply)-->如果连接成功返回true,否则返回false
if(!FTPReply.isPositiveCompletion(reply)){
ftp.disconnect();//说明连接失败,需要断开连接
return null;
}
} catch (IOException e) {
e.printStackTrace();
}
return ftp;
}
/**
* 关闭ftp连接
* @param ftp
*/
private static void closeFtp(FTPClient ftp) {
try {
if (ftp != null && ftp.isConnected())
ftp.disconnect();// 断开ftp的连接
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* 创建目录(有则切换目录,没有则创建目录)
* @param dir
* @return
*/
private static boolean createDir(String dir, FTPClient ftp) {
if (StringUtils.isBlank(dir))
return true;
String d;
try {
//目录编码,解决中文路径问题
d = new String(dir.toString().getBytes("GBK"),"iso-8859-1");
//尝试切入目录
if(ftp.changeWorkingDirectory(d))
return true;
String[] arr = dir.split("/");
StringBuffer sbfDir=new StringBuffer();
//循环生成子目录
for(String s : arr){
sbfDir.append("/");
sbfDir.append(s);
//目录编码,解决中文路径问题
d = new String(sbfDir.toString().getBytes("GBK"),"iso-8859-1");
//尝试切入目录
if(ftp.changeWorkingDirectory(d))
continue;
if(!ftp.makeDirectory(d)){
System.out.println("[失败]ftp创建目录:"+sbfDir.toString());
return false;
}
System.out.println("[成功]创建ftp目录:"+sbfDir.toString());
}
//将目录切换至指定路径
return ftp.changeWorkingDirectory(d);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}