import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
public class FtpUtil {
// 创建FTPClient对象
private int maxSize = 10240;//lt20140320 用于控制上传文件流的最大限制,单位是kb,页面显示限制为10M
private FTPClient ftp = new FTPClient();
private final static Logger logger = Logger.getLogger(FtpUtil.class);
/**
* Description: 向FTP服务器上传文件
* @param url FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param path FTP服务器保存目录
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回true,否则返回false
*/
public boolean uploadFile(String url, int port, String username,
String password, String path, String filename, InputStream input) {
// 初始表示上传失败
boolean success = false;
// 创建FTPClient对象
try {
int reply;
// 连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.connect(url, port);
//lt20140320 控制文件流的最大限制,页面显示限制为10M
ftp.setBufferSize(maxSize);
// 登录ftp
ftp.login(username, password);
// 看返回的值是不是230,如果是,表示登陆成功
reply = ftp.getReplyCode();
// 以2开头的返回值就会为真
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
//验证是否有该文件夹,有就转到,没有创建后转到根目录下
if (path != null && !"".equals(path)) {
if (!ftp.changeWorkingDirectory(path)) {
mkdirs(path);
if(!ftp.changeWorkingDirectory(path)){
logger.warn("ftp changeWorkingDirectory failed. path:"+path);
}
}
}
// 转到指定上传目录
//ftp.changeWorkingDirectory(path);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);//关键,必加,否则按照默认的ascii上传,会出现文件损坏的现象
// 将上传文件存储到指定目录
ftp.storeFile(filename, input);
// 退出ftp
ftp.logout();
// 表示上传成功
success = true;
} catch (IOException e) {
logger.error(e);
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (input !=null) {
// 关闭输入流
try {
input.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
return success;
}
/**
* 在服务器上建目录,中间目录不存在也自动创建
* @param path
*/
private boolean mkdirs(String path) throws IOException {
int index = 0;
String pathToMake = null;
boolean result = false;
//父目录
while((index = path.indexOf('/', index+1)) > 0){
pathToMake = path.substring(0,index);
result = ftp.makeDirectory(pathToMake);
if(!result){
logger.debug("ftp makeDirectory failed. path:"+pathToMake);
}
}
//目标目录
result = ftp.makeDirectory(path);
if(!result){
logger.warn("ftp makeDirectory failed. path:"+path);
}
return result;
}
/**
* @param url ftp服务器ip地址
* @param port ftp端口
* @param username 用户名
* @param password 密码
* @param filePath 删除文件路径
* @param fileName 要删除文件名
* @return
*/
public boolean deleteFile(String url, int port, String username,
String password, String filePath, String fileName) {
// 初始表示下载失败
boolean success = false;
try {
int reply;
// 连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.connect(url, port);
// 登录ftp
ftp.login(username, password);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
// 转到指定下载目录
if (filePath != null) {//验证是否有该文件夹,有就转到,没有创建后转到该目录下
if (!ftp.changeWorkingDirectory(filePath)) {
return success;
}
}
String fn = toFtpFilename(fileName);
// 删除文件
success = ftp.deleteFile(filePath + "/" + fn);
// 退出ftp
ftp.logout();
} catch (Exception e) {
logger.error(e);
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
private String toFtpFilename(String fileName) throws Exception {
return new String(fileName.getBytes("GBK"),"ISO8859-1");
}
/**
* Description: 从FTP服务器下载文件
* @param url FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param remotePath FTP服务器上的相对路径
* @param fileName 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @return
*/
public boolean downFileFromFtp(String url, int port, String username,
String password, String remotePath, String fileName, String localPath) {
// 初始表示下载失败
boolean success = false;
OutputStream is = null;
try {
int reply;
// 连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.connect(url, port);
// 登录ftp
ftp.login(username, password);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
// 转到指定下载目录
if (remotePath != null) {//验证是否有该文件夹,有就转到,没有创建后转到该目录下
if (!ftp.changeWorkingDirectory(remotePath)) {
return success;
}
}
//2015/4/28 不需要遍历,改为直接用文件名取
String fn = toFtpFilename(fileName);
// 根据绝对路径初始化文件
File localFile = new File(localPath + "/" + fileName);
// 输出流
is = new FileOutputStream(localFile);
// 下载文件
boolean retrieveResult = ftp.retrieveFile(fn, is);
if(!retrieveResult) {
return success;
}
is.close();
// 退出ftp
ftp.logout();
// 下载成功
success = true;
return success;
} catch (Exception e) {
logger.error(e);
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
try {
if(is != null) is.close();
} catch (Exception e2) {
}
}
return success;
}
/**
* 提供一个开放的logout接口
* @throws IOException
*/
public void ftpLogout() throws IOException{
this.ftp.logout();
}
public int getMaxSize() {
return maxSize;
}
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
}
package com.huntto.hii.ydzf.util;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import org.dom4j.Document;
import org.dom4j.Element;
import com.huntto.hii.webapp.action.BaseAction;
import com.huntto.hii.webapp.ftp.FtpUtil;
import com.huntto.hii.webapp.util.Dom4jUtils;
/**
* ftp配置文件
* @author li.di
*
*/
public class Ydzf_UploadPdf {
private String ip;// ftp服务器ip
private int port;
private String username;
private String password;
private String path;
private static final String FTPCONFIG = "ftpConfiguration.xml";
public static final String FileDownloadTempDir = ServletActionContext.getServletContext().getRealPath("/wenshu_pdf/");
public void initFtpServerParamsFromConfig() {
String xmlPath = BaseAction.class.getClassLoader().getResource("/").getPath() + FTPCONFIG;
if(xmlPath.contains("%20")){
xmlPath = xmlPath.replaceAll("%20", " ");
}
Document doc = Dom4jUtils.File2Document(xmlPath);
Element root = doc.getRootElement();
this.ip = root.element("ip").getText();
this.port = Integer.valueOf(root.element("port").getText());
this.username = root.element("username").getText();
this.password = root.element("password").getText();
this.path = root.element("path").getText();
}
/**
* 上传到FTP服务器上,服务器的配置查看ftpConfiguration.xml文件
* @param fileName 上传的文件名
* @param inputStream 要上传的文件输入流
* @param uploadModule 上传的模块,比如投诉举报传入“TSJB”
* @param identifer 上传附件到具体的文件夹名
* @return flag 上传是否成功
* @throws Exception
*/
protected boolean fileUploadtoFtpServer(String fileName, InputStream inputStream, String uploadModule, String identifer) throws Exception{
this.initFtpServerParamsFromConfig();
boolean flag=false;
try {
path = "/"+uploadModule+"/"+identifer;
FtpUtil ftpUtil = new FtpUtil();
String fiName = new String(fileName.getBytes(), "ISO8859-1");
flag = ftpUtil.uploadFile(ip, port, username, password,
path, fiName, inputStream);
System.out.println("附件上传成功?——"+flag);
return flag;
} catch (Exception e) {
e.printStackTrace();
return flag;
}
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public static String getFiledownloadtempdir() {
return FileDownloadTempDir;
}
}