https://github.com/xxxxxxx/springbootXr.git
1.pom.xml配置依赖jar包
<!-- ftp -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
2.新建Ftp.java
@Component
public class Ftp {
@Value("${ftp.ipAddr}")
private String ipAddr;//ip地址
@Value("${ftp.port}")
private Integer port;//端口号
@Value("${ftp.userName}")
private String userName;//用户名
@Value("${ftp.pwd}")
private String pwd;//密码
@Value("${ftp.path}")
private String path;//ftp路径
3.配置文件application.properties
#链接ftp
ftp.ipAddr=xxx
ftp.port=638
ftp.userName=xx
ftp.pwd =xxx
ftp.path =/\u7ED8\u672C\u9605\u8BFB
4. FtpUtil.java实体类
package com.eebbk.englishbook.admin.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import com.eebbk.edu.common.log.LogUtil;
import com.eebbk.edu.common.log.Logger;
import com.eebbk.englishbook.admin.service.impl.BoyunHuiBenServiceImpl;
import com.eebbk.englishbook.admin.vo.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.beans.factory.annotation.Autowired;
/**
*@Description:
*@author:kry
*@Creattime:2019年8月16日 下午3:51:25
*@company:
*/
public class FtpUtil {
private static final Logger logger = LogUtil.getLogger(FtpUtil.class);
private static FTPClient ftp;
//FTPClient默认编码
public static String defaulegbkEncode(String param)
throws UnsupportedEncodingException
{
return new String(param.getBytes(), "ISO-8859-1");
}
//
public static String gbkEncodeUTF8(String param)
throws UnsupportedEncodingException
{
return new String(param.getBytes("ISO-8859-1"), "utf-8");
}
/**
* 获取ftp连接
* @param f
* @return
* @throws Exception
*/
public static boolean connectFtp(Ftp f) throws Exception{
ftp=new FTPClient();
boolean flag=false;
int reply;
try{
if (f.getPath()==null) {
ftp.connect(f.getIpAddr(),21);
}else{
ftp.connect(f.getIpAddr(),Integer.valueOf(f.getPort()));
}
//ftp登陆//编码不添加,使用默认的
//ftp.setControlEncoding("utf-8");
ftp.login(f.getUserName(), f.getPwd());
ftp.enterLocalPassiveMode();//不加此行 String[] files=f.list();会执行不了
//设置文件传输类型
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
//检查延时
reply = ftp.getReplyCode();
//如果延时不在200到300之间,就关闭连接
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return flag;
}
//转成默认编码
String path= defaulegbkEncode(f.getPath());
ftp.changeWorkingDirectory(path); //path要和ftp的编码一致,本方法没加使用默认的
flag = true;
return flag;
}catch(Exception e){
throw new Exception(e.getMessage());
}
}
/**
* 关闭ftp连接
*/
public static void closeFtp(){
if (ftp!=null && ftp.isConnected()) {
try {
ftp.logout();
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* ftp上传文件
* @param f
* @throws Exception
*/
public static void upload(File f) throws Exception{
if (f.isDirectory()) {
ftp.makeDirectory(f.getName());
String name= defaulegbkEncode(f.getName());
ftp.changeWorkingDirectory(name);
//返回目录名和文件名组成的字符串数组
String[] files=f.list();
for(String fstr : files){
File file1=new File(f.getPath()+"/"+fstr);
if (file1.isDirectory()) {
upload(file1);
ftp.changeToParentDirectory();
}else{
File file2=new File(f.getPath()+"/"+fstr);
FileInputStream input=new FileInputStream(file2);
//上传使用默认编码
ftp.storeFile(defaulegbkEncode(file2.getName()),input);
input.close();
}
}
}else{
File file2=new File(f.getPath());
FileInputStream input=new FileInputStream(file2);
ftp.storeFile(defaulegbkEncode(file2.getName()),input);
input.close();
}
}
/**
* 下载链接配置
* @param f
* @param localBaseDir 本地目录
* @param remoteBaseDir 远程目录
* @throws Exception
*/
public static boolean startDown(Ftp f,String filename,String localBaseDir,String remoteBaseDir ) throws Exception{
if (FtpUtil.connectFtp(f)) {
System.out.println(ftp.getReplyCode());
try {
FTPFile[] files = null;
String name= defaulegbkEncode(remoteBaseDir);
boolean changedir = ftp.changeWorkingDirectory(name);
if (changedir) {
//ftp.setControlEncoding("utf-8");
files = ftp.listFiles();
for (int i = 0; i < files.length; i++) {
try{
String fileName= files[i].getName();
fileName= gbkEncodeUTF8(fileName);
if(filename.equals(fileName)){
downloadFile(files[i], localBaseDir, remoteBaseDir);
return true;
}
}catch(Exception e){
logger.error(e);
logger.error("<"+files[i].getName()+">下载失败");
}
}
}
} catch (Exception e) {
logger.error(e);
logger.error("下载过程中出现异常");
}
}else{
logger.error("链接失败!");
}
return false;
}
/**
*
* 下载FTP文件
* 当你需要下载FTP文件的时候,调用此方法
* 根据获取的文件名,本地地址,远程地址进行下载
*
* @param ftpFile
* @param relativeLocalPath
* @param relativeRemotePath
* @throws UnsupportedEncodingException
*/
private static void downloadFile(FTPFile ftpFile, String relativeLocalPath,String relativeRemotePath) throws UnsupportedEncodingException {
if (ftpFile.isFile()) {
if (gbkEncodeUTF8(ftpFile.getName()).indexOf("?") == -1) {
OutputStream outputStream = null;
try {
File entryDir = new File(relativeLocalPath);
//如果文件夹路径不存在,则创建文件夹
if (!entryDir.exists() || !entryDir.isDirectory())
{
entryDir.mkdirs();
}
if(!relativeLocalPath.endsWith("\\")){
relativeLocalPath+="\\";
}
File locaFile= new File(relativeLocalPath+ gbkEncodeUTF8(ftpFile.getName()));
//判断文件是否存在,存在则返回
if(locaFile.exists()){
return;
}else{
outputStream = new FileOutputStream(relativeLocalPath+ gbkEncodeUTF8(ftpFile.getName()));
ftp.retrieveFile(ftpFile.getName(), outputStream);
outputStream.flush();
outputStream.close();
}
} catch (Exception e) {
logger.error(e);
} finally {
try {
if (outputStream != null){
outputStream.close();
}
} catch (IOException e) {
logger.error("输出文件流异常");
}
}
}
} else {
String newlocalRelatePath = relativeLocalPath + gbkEncodeUTF8(ftpFile.getName());
String newRemote = new String(relativeRemotePath+ gbkEncodeUTF8(ftpFile.getName()));
File fl = new File(newlocalRelatePath);
if (!fl.exists()) {
fl.mkdirs();
}
try {
newlocalRelatePath = newlocalRelatePath + '/';
newRemote = newRemote + "/";
String currentWorkDir = gbkEncodeUTF8(ftpFile.getName()).toString();
boolean changedir = ftp.changeWorkingDirectory(currentWorkDir);
if (changedir) {
FTPFile[] files = null;
files = ftp.listFiles();
for (int i = 0; i < files.length; i++) {
downloadFile(files[i], newlocalRelatePath, newRemote);
}
}
if (changedir){
ftp.changeToParentDirectory();
}
} catch (Exception e) {
logger.error(e);
}
}
}
/**
* 先配置下载链接,在下载文件。 调用了startDown和downloadFile写的方法
* @param f
* @param savepath
* @param filename
* @return
* @throws Exception
*/
public static boolean downfile(Ftp f,String savepath,String filename) throws Exception{
try{
String addr= f.getIpAddr();
// FtpUtil.connectFtp(f);
//FtpUtil.upload(file);//把文件上传在ftp上
return FtpUtil.startDown(f, filename ,savepath, f.getPath());//下载ftp文件测试
}catch(Exception e){
throw new Exception(e.getMessage());
}
}
}
5.调用方法
/**
* 从ftp下载
*/
@Override
public String downloadZip(String bookName, HttpServletResponse response) {
String result="";
try {
//下载
//sFtpUtil.connectFtp(ftp);
if(!bookName.endsWith(".zip")){
bookName+=".zip";
}
FtpUtil.downfile(ftp,"D:\\绘本阅读zip下载",bookName);
result="下载成功,文件路径 D:\\绘本阅读zip下载"+bookName;
} catch (Exception e) {
result="下载失败";
e.printStackTrace();
}finally{
FtpUtil.closeFtp();
}
return ResultVoTemplate.outputSuccess(result);
}
@Override
public String uploadZip(MultipartFile file, HttpServletResponse response) {
String result="";
try {
FtpUtil.connectFtp(ftp);
//MultipartFile 转File 生成临时文件
String fileName = file.getOriginalFilename();
byte[] b = file.getBytes();
File fi = new File("D:\\"+fileName);
FileOutputStream fou = new FileOutputStream(fi);
fou.write(b);
fou.close();
FtpUtil.upload(fi);
//程序结束时,删除临时文件
if (fi.exists()) {
fi.delete();
}
result="上传文件至ftp成功!";
} catch (Exception e) {
result="上传文件至ftp失败!";
e.printStackTrace();
}finally{
FtpUtil.closeFtp();
}
return ResultVoTemplate.outputSuccess(result);
}