怎么用JSP把本地的文件夹上传到FTP服务器?
前段时间做了一个文件上传ftp功能,你参照一下
package comftpupload;
import javaioFile;
import javaioFileInputStream;
import javaioFileOutputStream;
import javaioIOException;
import javaioInputStream;
import javaioOutputStream;
import orgapachecommonsioFileUtils;
import orgapachecommonsioIOUtils;
import orgapachecommonsnetftpFTPClient;
import orgapachecommonsnetftpFTPFile;
import orgapachecommonsnetftpFTPReply;
public class FTPUpload {
private FTPClient ftpClient = null;
private OutputStream outSteam = null;
/
ftp服务器地址
/
private String hostname = "19216812";
/
ftp服务器端口
/
int port = 21;
/
登录名
/
private String username = "admin";
/
登录密码
/
private String password = "admin";
/
需要访问的远程目录
/
private String remoteDir = "/home/demo";
public FTPUpload() { }
public FTPUpload(String hostname, int port, String username, String password, String remoteDir){
thishostname = hostname;
thisport = port;
thisusername = username;
thispassword = password;
thisremoteDir = remoteDir;
}
/
连接FTP服务器 并登录
@param hostName FTP服务器hostname
@param port FTP服务器端口
@param username FTP登录账号
@param password FTP登录密码
/
private FTPClient connectFTPServer() {
try {
//1创建FTPClient对象
ftpClient = new FTPClient();
//2连接FTP服务器
// 如果采用默认端口,可以使用ftpconnect(url)的方式直接连接FTP服务器
ftpClientconnect(hostname, port); //链接到ftp服务器
// Systemoutprintln("连接到ftp服务器地址 --> ftp://" + hostName + ":" + port + " 成功开始登录");
//3判断连接ftp服务器是否成功
int reply = ftpClientgetReplyCode();
// Systemoutprintln("以2开头的返回值就会为真:" + reply);
//以2开头的返回值就会为真
if (!FTPReplyisPositiveCompletion(reply)) {
ftpClientdisconnect();
return null;
}
//4登录FTP服务器用户名 密码
ftpClientlogin(username, password);
Systemoutprintln("登录成功" );
return ftpClient;
} catch (Exception e) {
eprintStackTrace();
ftpClient = null;
return ftpClient;
}
}
/
向FTP服务器上传文件
@param filePathName 上传文件的全路径名称
@return 成功返回true,否则返回false
/
public boolean uploadFile(String filePathName) {
// 初始表示上传失败
boolean success = false;
try {
// 创建FTPClient对象
ftpClient = connectFTPServer();
//创建文件夹
boolean flag = ftpClientmakeDirectory(remoteDir);
if(flag) {
Systemoutprintln("创建文件夹:" + remoteDir );
}
// 转到指定上传目录
boolean flag0 = ftpClientchangeWorkingDirectory(remoteDir);
// 将上传文件存储到指定目录
if(filePathName == null || filePathNamelength() == 0){
return success;
}
String filename = filePathNamesubstring(filePathNamereplace("\\", "/")lastIndexOf("/") + 1, filePathNamelength());
InputStream input = new FileInputStream(new File(filePathName));
// ftpClientsetBufferSize(1024);
// ftpClientsetControlEncoding("GBK");
// ftpClientsetFileType(FTPClientBINARY_FILE_TYPE);//设置文件类型
boolean flag1 = ftpClientstoreFile(filename, input);
Systemoutprintln("转到指定上传目录:" + flag0 + " 将上传文件存储到指定目录:" + flag1);
inputclose(); // 关闭输入流
ftpClientlogout(); // 退出ftp
success = true; // 表示上传成功
} catch (Exception e) {
eprintStackTrace();
} finally {
if (ftpClientisConnected()) {
try {
ftpClientdisconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
/
从FTP服务器指定目录下载文件 到本地目录中 OK
@param fileName 要下载的文件名
@param localPath 下载后保存到本地的路径
@param showlist 下载时是否显示列表 ( true 显示 )
@return
/
public boolean downFile(String fileName, String localPath, boolean showlist) {
// 初始表示下载失败
boolean success = false;
if(fileName == null || fileNamelength() == 0 || localPath == null || localPathlength() == 0){
return success;
}
try {
File file = new File(localPath);
if(!fileisDirectory()){
filemkdir();
}
// 创建FTPClient对象
ftpClient = connectFTPServer();
// 转到指定下载目录
boolean flag = ftpClientchangeWorkingDirectory(remoteDir);
if(!flag) {
Systemoutprintln("目录:" + remoteDir +"不存在!");
return success;
}
// 列出该目录下所有文件
FTPFile[] remoteFiles = ftpClientlistFiles();
// 遍历所有文件,找到指定的文件
if(showlist){
Systemoutprintln("目录" + remoteDir + "下的文件:");
}
for (FTPFile ftpFile : remoteFiles) {
String name = ftpFilegetName();
if(showlist){
long length = ftpFilegetSize();
String readableLength = FileUtilsbyteCountToDisplaySize(length);
Systemoutprintln(name + ":\t\t" + readableLength);
}
if (nameequals(fileName)) {
// 根据绝对路径初始化文件
File localFile = new File(localPath + "/" + name);
// 输出流
OutputStream is = new FileOutputStream(localFile);
// 下载文件
ftpClientretrieveFile(name, is);
isclose();
}
}
// 退出ftp
ftpClientlogout();
// 下载成功
success = true;
} catch (IOException e) {
eprintStackTrace();
} finally {
if (ftpClientisConnected()) {
try {
ftpClientdisconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
/
显示FTP服务器指定文件夹中的文件及大小 OK
@return
/
private boolean showFileList() {
// 初始表示失败
boolean success = false;
try {
ftpClient = connectFTPServer();
FTPFile[] remoteFiles = null;
// 转到指定下载目录
boolean flag = ftpClientchangeWorkingDirectory(remoteDir);
if(!flag) {
Systemoutprintln("目录:" + remoteDir +"不存在!");
return success;
} else{
remoteFiles = ftpClientlistFiles(remoteDir);
Systemoutprintln("目录" + remoteDir + "下的文件:");
}
if(remoteFiles != null) {
for(int i=0;i < remoteFileslength; i++){
String name = remoteFiles[i]getName();
long length = remoteFiles[i]getSize();
String readableLength = FileUtilsbyteCountToDisplaySize(length);
Systemoutprintln(name + ":\t\t" + readableLength);
}
}
// 表示成功
success = true;
} catch (Exception e) {
eprintStackTrace();
} finally {
//使用IO包关闭流
IOUtilscloseQuietly(outSteam);
try {
ftpClientdisconnect();
} catch (IOException ioe) {
ioeprintStackTrace();
}
}
return success;
}
public static void main(String[] args) {
FTPUpload ftp = new FTPUpload();
ftpuploadFile("c:////test////bgsspjar");
}
}
准备条件:java实现ftp上传用到了commons-net-33jar包
首先建立ftphost连接
public boolean connect(String path, String addr, int port, String username, String password) {try {
//FTPClient ftp = new FTPHTTPClient(addr, port, username, password);
ftp = new FTPClient();
int reply;
ftpconnect(addr);
Systemoutprintln("连接到:" + addr + ":" + port);
Systemoutprint(ftpgetReplyString());
reply = ftpgetReplyCode();
if (!FTPReplyisPositiveCompletion(reply)) {
ftpdisconnect();
Systemerrprintln("FTP目标服务器积极拒绝");
Systemexit(1);
return false;
}else{
ftplogin(username, password);
ftpenterLocalPassiveMode();
ftpsetFileType(FTPClientBINARY_FILE_TYPE);
ftpchangeWorkingDirectory(path);
Systemoutprintln("已连接:" + addr + ":" + port);
return true;
}
} catch (Exception ex) {
exprintStackTrace();
Systemoutprintln(exgetMessage());
return false;
}
}
然后再利用ftpclient的makeDirectory方法创建文件夹
public void createDir(String dirname){try{
ftpmakeDirectory(dirname);
Systemoutprintln("在目标服务器上成功建立了文件夹: " + dirname);
}catch(Exception ex){
Systemoutprintln(exgetMessage());
}
}
断开host连接
public void disconnect(){try {
ftpdisconnect();
} catch (IOException e) {
eprintStackTrace();
}
}
最后是程序的调用方法
public static void main(String[] args) {FtpUploadTest ftpupload = new FtpUploadTest();
if(ftpuploadconnect("", "172398x", 20, "administrator", "abc@123")){
ftpuploadcreateDir("/UPLOAD");
ftpuploaddisconnect();
}
}
0条评论