|
这个是上传文件的工具类,也很简单
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
/**
*
* @author lan
*/
public final class FTPUtil {
private static final Log log = LogFactory.getLog(FTPUtil.class);
public static boolean upload(String host, int port, String user, String pwd, String targetPath, String name, InputStream is) {
if (name == null || is == null) {
return false;
}
FTPClient ftp = new FTPClient();
try {
ftp.connect(host, port);
ftp.login(user, pwd);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
log.warn("ftp login failed");
return false;
}
if (targetPath != null) {//验证是否有该文件夹,有就转到,没有创建后转到该目录下
if (!ftp.changeWorkingDirectory(targetPath)) {
ftp.makeDirectory(targetPath);
ftp.changeWorkingDirectory(targetPath);
}
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);//关键,必加,否则按照默认的ascii上传,会出现文件损坏的现象
ftp.storeFile(name, is);
is.close();
ftp.logout();
log.info("upload " + name + " success");
return true;
} catch (SocketException ex) {
log.error(ex.getMessage(), ex);
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
}
}
}
return false;
}
public static boolean upload(String host, int port, String user, String pwd, String targetPath, File f) {
InputStream is = null;
try {
is = new FileInputStream(f);
} catch (FileNotFoundException ex) {
log.error(ex.getMessage(), ex);
}
return upload(host, port, user, pwd, targetPath, f.getName(), is);
}
}
|
|
|