注:每次请求都是先登陆服务器的,代码中报错部分代码无用,先删除
ftp的用户信息可以写的配置文件中,该代码写在了redis中,请自行修改
package com.founder.zxb.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
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.beans.factory.annotation.Autowired;
import com.founder.zxb.model.SysConfIg;
import com.founder.zxb.redis.service.CacheService;
import com.founder.zxb.services.impl.SysConfIgServiceImpl;
public class FtpUtil {
/**
* Description: 向FTP服务器上传文件
* @param host FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param basePath FTP服务器基础目录
* @param filePath FTP服务器文件存放路径。文件的路径为basePath+filePath
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回true,否则返回false
*/
public static boolean uploadFile(String filePath, String filename, InputStream input) {
boolean result = false;
FTPClient ftp = loginFtp();
if(ftp==null) {
return false;
}
try {
//切换到上传目录
if (!ftp.changeWorkingDirectory("/"+filePath)) {
//如果目录不存在创建目录
String[] dirs = filePath.split("/");
String tempPath = "/";
for (String dir : dirs) {
if (null == dir || "".equals(dir)) continue;
tempPath += "/" + dir;
if (!ftp.changeWorkingDirectory(tempPath)) { //进不去目录,说明该目录不存在
if (!ftp.makeDirectory(tempPath)) { //创建目录
//如果创建文件目录失败,则返回
System.out.println("创建文件目录"+tempPath+"失败");
return result;
} else {
//目录存在,则直接进入该目录
ftp.changeWorkingDirectory(tempPath);
}
}
}
}
//设置上传文件的类型为二进制类型
ftp.setFileType(FTP.BINARY_FILE_TYPE);
//上传文件
//if (!ftp.storeFile(new String(filename.getBytes("GBK"), "iso-8859-1"), input)) {GBK(gb2312)
if (!ftp.storeFile(new String(filename.getBytes(), "iso-8859-1"), input)) {
return result;
}
input.close();
ftp.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
/**
* Description: 从FTP服务器下载文件
* @param host FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param remotePath FTP服务器上的相对路径
* @param fileName 要下载的文件名
* @return
*/
public static boolean downloadFile(String remotePath,String fileName ,HttpServletResponse response) {
boolean result = false;
FTPClient ftp = loginFtp();
if(ftp==null) {
return false;
}
try {
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
ftp.enterLocalPassiveMode();
FTPFile[] fs = ftp.listFiles(remotePath);
for (FTPFile ff : fs) {
if (ff.getName().equals(new String(fileName.getBytes(),"ISO8859-1"))) {
InputStream fis = ftp.retrieveFileStream(ff.getName());
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"),"ISO8859-1"));
response.setContentType("application/octet-stream");
OutputStream out = response.getOutputStream();
byte[] b = new byte[2048];
int len;
while ((len = fis.read(b)) != -1) {
out.write(b, 0, len);
}
fis.close();
out.close();
result = true;
}
}
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
/**
* 下载文件返回文件流
* @param remotePath
* @param fileName
* @param response
* @return
*/
public static InputStream downloadFile(String remotePath,String fileName) {
FTPClient ftp = loginFtp();
if(ftp==null) {
return null;
}
try {
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(new String(fileName.getBytes(),"ISO8859-1"))) {
InputStream fis = ftp.retrieveFileStream(ff.getName());
return fis;
}
}
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return null;
}
/**
*
* @param host
* @param port
* @param username
* @param password
* @param remotePath
* @param fileName
* @param response
* @return
*/
public static boolean deleteFile(String remotePath,String fileName ) {
boolean result = false;
FTPClient ftp = loginFtp();
if(ftp==null) {
return false;
}
try {
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
//删除文件
ftp.dele(fileName);
ftp.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
//ftp上传文件测试main函数
// public static void six() {
// try {
// FileInputStream in=new FileInputStream(new File("C:\\Users\\bai\\FtpSite\\123.txt"));
// boolean flag = uploadFile("172.19.203.84", 21, "ftpuser", "admin", "/","/2017/11/19", "hello.txt", in);
// System.out.println(flag);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// }
//
private static FTPClient loginFtp() {
CacheService cacheService = (CacheService)SpringContextUtils.getBean(CacheService.class);
SysConfIgServiceImpl sysConfIgServiceImpl = (SysConfIgServiceImpl)SpringContextUtils.getBean(SysConfIgServiceImpl.class);
FTPClient ftp = new FTPClient();
int reply;
Map<String,String> map=cacheService.get("ftp_map");
if(map==null) {
map=new HashMap();
List<SysConfIg> list=sysConfIgServiceImpl.findFtpByCode("ftp");
for(SysConfIg sysConfIg:list) {
map.put(sysConfIg.getName(), sysConfIg.getValue());
}
cacheService.set("ftp_map", map);
}
try {
ftp.connect(map.get("host"), Integer.valueOf(map.get("port")));
ftp.login(map.get("userName"), map.get("passWord"));// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
return ftp;
}
}