1。pom.xml 加入支持
<!-- https://mvnrepository.com/artifact/commons-net/commons-net ftp上传-->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
2。controller
import com.example.appserve.entity.Ftp;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Controller
public class controller {
@RequestMapping("/file")
public void saveGrzlq(@RequestParam("lttp") MultipartFile lttp, HttpServletResponse response) throws IOException {
String tpImg = "";
Map<String, Object> reMap = new HashMap<String, Object>();
String zpljurl = "";
// 判断是否有头像照片,如果有则上传
if (null != lttp && !lttp.isEmpty()) {
String lttpFileName = lttp.getOriginalFilename();
//ftp 的ip地址端口号和账号密码
Ftp ftp = new Ftp("ip", 端口号,"user", "password");
ftp.ftpLogin();
zpljurl = ftp.uploadFile2(lttp.getInputStream(), "lttp",lttpFileName);
ftp.ftpLogOut();
//tpimg 是访问照片的路径
tpImg += "http://ip:端口号/filebase/" + zpljurl;
}
System.out.println(tpImg);
}
}
3。Entity下的Ftp.java 公共类 复制粘贴就行啦
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class Ftp {
private FTPClient ftpClient;
private String strIp;//IP地址
private int intPort;//端口号
private String user;//y用户
private String password;//密码
//private static Logger logger = Logger.getLogger(Ftp.class.getName());
/* *
* Ftp构造函数
*/
public Ftp(String strIp, int intPort, String user, String Password) {
this.strIp = strIp;
this.intPort = intPort;
this.user = user;
this.password = Password;
this.ftpClient = new FTPClient();
}
/**
* @return 判断是否登入成功
* */
public boolean ftpLogin() {
boolean isLogin = false;
FTPClientConfig ftpClientConfig = new FTPClientConfig();
ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
this.ftpClient.setControlEncoding("GBK");
this.ftpClient.configure(ftpClientConfig);
try {
if (this.intPort > 0) {
this.ftpClient.connect(this.strIp, this.intPort);
} else {
this.ftpClient.connect(this.strIp);
}
// FTP服务器连接回答
int reply = this.ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
this.ftpClient.disconnect();
//System.out.println("登录FTP服务失败!");
return isLogin;
}
this.ftpClient.login(this.user, this.password);
// 设置传输协议
this.ftpClient.enterLocalPassiveMode();
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//System.out.println("恭喜" + this.user + "成功登陆FTP服务器");
isLogin = true;
} catch (Exception e) {
e.printStackTrace();
//System.out.println(this.user + "登录FTP服务失败!" + e.getMessage());
}
this.ftpClient.setBufferSize(1024 * 2);
this.ftpClient.setDataTimeout(30 * 1000);
return isLogin;
}
/**
* @退出关闭服务器链接
* */
public void ftpLogOut() {
if (null != this.ftpClient && this.ftpClient.isConnected()) {
try {
boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
if (reuslt) {
//System.out.println("成功退出服务器");
}
} catch (IOException e) {
e.printStackTrace();
//System.out.println("退出FTP服务器异常!" + e.getMessage());
} finally {
try {
this.ftpClient.disconnect();// 关闭FTP服务器的连接
} catch (IOException e) {
e.printStackTrace();
//System.out.println("关闭FTP服务器的连接异常!");
}
}
}
}
/***
* 上传Ftp文件
* @param localFile 当地文件
* @param //romotUpLoadePath上传服务器路径 - 应该以/结束
* */
public boolean uploadFile(File localFile, String romotUpLoadePath) {
BufferedInputStream inStream = null;
boolean success = false;
try {
boolean change = this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
if(!change){
this.ftpClient.makeDirectory(romotUpLoadePath);
}
change = this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
inStream = new BufferedInputStream(new FileInputStream(localFile));
//System.out.println(localFile.getName() + "开始上传.....");
localFile = rename(localFile);//重命名
System.out.println(localFile.getName());
success = this.ftpClient.storeFile(localFile.getName(), inStream);
if (success == true) {
//System.out.println(localFile.getName() + "上传成功");
return success;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
//System.out.println(localFile + "未找到");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return success;
}
/**
* 根据InputStream流上传FTP 返回以时间戳定义的文件名 1层目录
* @param in
* @param romotUpLoadePath
* @param fileName
* @return
*/
public String uploadFile2(InputStream in, String romotUpLoadePath, String fileName) {
String str = "";
str = rename2(fileName);
try {
// this.ftpClient.enterLocalActiveMode(); //主动模式
this.ftpClient.enterLocalPassiveMode(); //被动模式
this.ftpClient.setRemoteVerificationEnabled(false);
if(romotUpLoadePath!=null){
boolean change = this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
if(!change){
this.ftpClient.makeDirectory(romotUpLoadePath);
}
this.ftpClient.changeWorkingDirectory(romotUpLoadePath);
}
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
this.ftpClient.storeFile(str, in);
System.out.println("已上传到服务器");
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
String lj=romotUpLoadePath+"/"+str;
return lj;
}
/**
* 根据InputStream流上传FTP 返回以时间戳定义的文件名 2 两层目录
* @param in
* @param //romotUpLoadePath
* @param fileName
* @return
*/
public String uploadFile2(InputStream in, String romotUpLoadePath1,String romotUpLoadePath2, String fileName) {
String str = "";
str = rename2(fileName);
try {
this.ftpClient.enterLocalActiveMode(); //主动模式
// this.ftpClient.enterLocalPassiveMode(); //被动模式
this.ftpClient.setRemoteVerificationEnabled(false);
if(romotUpLoadePath1!=null&&!"".equals(romotUpLoadePath1)&&romotUpLoadePath2!=null&&!"".equals(romotUpLoadePath2)){
if(romotUpLoadePath1.length()>0){
boolean change = this.ftpClient.changeWorkingDirectory(romotUpLoadePath1);// 改变工作路径
if(!change){
this.ftpClient.makeDirectory(romotUpLoadePath1);
}
this.ftpClient.changeWorkingDirectory(romotUpLoadePath1);
}
if(romotUpLoadePath2.length()>0){
boolean change1 = this.ftpClient.changeWorkingDirectory(romotUpLoadePath2);// 改变工作路径
if(!change1){
this.ftpClient.makeDirectory(romotUpLoadePath2);
}
this.ftpClient.changeWorkingDirectory(romotUpLoadePath2);
}
}
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
this.ftpClient.storeFile(str, in);
System.out.println("已上传到服务器");
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
String lj=romotUpLoadePath1+"/"+romotUpLoadePath2+"/"+str;
return lj;
}
//上传文件到多级的目录 romotUpLoadePath :目录/目录
public String multistageCatalog(InputStream in, String romotUpLoadePath, String fileName) {
String str = "";
str = rename2(fileName);
try {
// this.ftpClient.enterLocalActiveMode(); //主动模式
this.ftpClient.enterLocalPassiveMode(); //被动模式
this.ftpClient.setRemoteVerificationEnabled(false);
if(romotUpLoadePath!=null){
String path[] = romotUpLoadePath.split("/");
for (int i = 0; i < path.length; i++) {
boolean change = this.ftpClient.changeWorkingDirectory(path[i]);// 改变工作路径
if(!change){
this.ftpClient.makeDirectory(path[i]);
}
this.ftpClient.changeWorkingDirectory(path[i]);
}
}
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
this.ftpClient.storeFile(str, in);
System.out.println("已上传到服务器");
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
String lj=romotUpLoadePath+"/"+str;
return lj;
}
/***
* 下载文件
* @param remoteFileName 待下载文件名称
* @param localDires 下载到当地那个路径下
* @param remoteDownLoadPath remoteFileName所在的路径
* */
public boolean downloadFile(String remoteFileName, String localDires,
String remoteDownLoadPath) {
String strFilePath = localDires + remoteFileName;
BufferedOutputStream outStream = null;
boolean success = false;
try {
this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
outStream = new BufferedOutputStream(new FileOutputStream(
strFilePath));
//logger.info(remoteFileName + "开始下载....");
success = this.ftpClient.retrieveFile(remoteFileName, outStream);
if (success == true) {
//logger.info(remoteFileName + "成功下载到" + strFilePath);
return success;
}
} catch (Exception e) {
e.printStackTrace();
//logger.error(remoteFileName + "下载失败");
} finally {
if (null != outStream) {
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (success == false) {
//logger.error(remoteFileName + "下载失败!!!");
}
return success;
}
/***
* 下载文件
* @param remoteFileName 待下载文件名称
* @param localDires 下载到当地那个路径下
* @param remoteDownLoadPath remoteFileName所在的路径
* */
public boolean downloadFile2(String remoteFileName, String localDires,
String remoteDownLoadPath) {
String strFilePath = localDires + remoteFileName;
BufferedOutputStream outStream = null;
boolean success = false;
try {
ftpClient.enterLocalPassiveMode();
this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
outStream = new BufferedOutputStream(new FileOutputStream(strFilePath));
success = this.ftpClient.retrieveFile(remoteFileName, outStream);
if (success == true) {
return success;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != outStream) {
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (success == false) {
//logger.error(remoteFileName + "下载失败!!!");
}
return success;
}
/***
* @上传文件夹
* @param localDirectory
* 当地文件夹
* @param remoteDirectoryPath
* Ftp 服务器路径 以目录"/"结束
* */
public boolean uploadDirectory(String localDirectory,
String remoteDirectoryPath) {
File src = new File(localDirectory);
try {
remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
this.ftpClient.makeDirectory(remoteDirectoryPath);
// ftpClient.listDirectories();
} catch (IOException e) {
e.printStackTrace();
System.out.println(remoteDirectoryPath + "目录创建失败");
//logger.info(remoteDirectoryPath + "目录创建失败");
}
File[] allFile = src.listFiles();
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (!allFile[currentFile].isDirectory()) {
String srcName = allFile[currentFile].getPath().toString();
uploadFile(new File(srcName), remoteDirectoryPath);
}
}
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (allFile[currentFile].isDirectory()) {
// 递归
uploadDirectory(allFile[currentFile].getPath().toString(),
remoteDirectoryPath);
}
}
return true;
}
/***
* @下载文件夹
* @param //localDirectoryPath本地地址
* @param remoteDirectory 远程文件夹
* */
public boolean downLoadDirectory(String localDirectoryPath,String remoteDirectory) {
try {
String fileName = new File(remoteDirectory).getName();
localDirectoryPath = localDirectoryPath + fileName + "//";
new File(localDirectoryPath).mkdirs();
FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (!allFile[currentFile].isDirectory()) {
downloadFile(allFile[currentFile].getName(),localDirectoryPath, remoteDirectory);
}
}
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (allFile[currentFile].isDirectory()) {
String strremoteDirectoryPath = remoteDirectory + "/"+ allFile[currentFile].getName();
downLoadDirectory(localDirectoryPath,strremoteDirectoryPath);
}
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("下载文件夹失败");
//logger.info("下载文件夹失败");
return false;
}
return true;
}
/**
* @FTP删除文件
* @param remote 删除文件路径
* @return
* @throws IOException
*/
/**
* @param url FTP服务器IP地址
* @param port FTP服务器端口
* @param username FTP服务器登录名
* @param password FTP服务器密码
* @param remotePath 远程文件路径
* @param fileName 待删除的文件名
* @return
* @see [类、类#方法、类#成员]
*/
public static boolean deleteFtpFile(String url, int port, String username, String password, String remotePath,
String fileName)
{
boolean success = false;
FTPClient ftp = new FTPClient();
try
{
int reply;
// 连接FTP服务器
if (port > -1)
{
ftp.connect(url, port);
}
else
{
ftp.connect(url);
}
// 登录
ftp.login(username, password);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
ftp.disconnect();
return success;
}
// 转移到FTP服务器目录
ftp.changeWorkingDirectory(remotePath);
String fileName_str = new String(fileName.getBytes("GBK"), "ISO-8859-1");
success = ftp.deleteFile("/" + fileName_str);
//success = ftp.deleteFile(fileName_str.substring(1,fileName_str.length())); //linux环境
ftp.logout();
}
catch (IOException e)
{
success = false;
}
return success;
}
// FtpClient的Set 和 Get 函数
public FTPClient getFtpClient() {
return ftpClient;
}
public void setFtpClient(FTPClient ftpClient) {
this.ftpClient = ftpClient;
}
/**
* 文件重命名
* @param file
* @return
*/
public static File rename(File file) {
String ext="";
String body="";
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHH");//设置日期格式
String time = df.format(new Date());
body = String.valueOf(new Date().getTime());
int pot=file.getName().lastIndexOf(".");
if(pot!=-1){
ext=file.getName().substring(pot);
}else{
ext="";
}
String newName=time+body+ext;
file=new File(file.getParent(),newName);
return file;
}
/**
* 文件重命名
* @param //file
* @return
*/
public static String rename2(String str) {
String ext="";
String body="";
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHH");//设置日期格式
String time = df.format(new Date());
body = String.valueOf(new Date().getTime());
int pot=str.lastIndexOf(".");
if(pot!=-1){
ext=str.substring(pot);
}else{
ext="";
}
String newName=time+body+ext;
return newName;
}
/**
* 查看ftp上所有的文件
*/
public String[] listRemoteAllFiles(String path){
String[] names = {};
try{
ftpClient.changeWorkingDirectory(path);
names = this.ftpClient.listNames();
}catch (Exception e) {
e.printStackTrace();
}
return names;
}
}