JSP_FTP

来源:互联网 发布:mysql查询顺序 编辑:程序博客网 时间:2024/06/04 18:46

转自http://blog.csdn.net/rocket5725/article/details/4177090

感谢IT的前辈

时间:2009-05-13  14:23:19

内容:在JSP中实现FTP上传和下载

虽然已经实现了FTP上传,但是目前却只能上传英文路径,该问题依旧等待解决的方案

一、所需软件:

FTP服务器:ServUSetup.exe 下载地址为:http://www.rhinosoft.com/__release/ServUSetup.exe

Java FTP 库edtFTPj/Free:下载地址为:http://www.enterprisedt.com/products/edtftpj/download/edtftpj.zip

二、edtFTPj/Free实现了以下功能

1、上传指定文件夹(包括子文件和文件夹) uploadFolder(String folderName, String ftpPath)

2、下载FTP上指定的文件夹 downloadFolder(String ftppath, String outdir, String ftpdir)

3、上传指定文件夹下的所有文件到FTP指定目录下 uploadAllFilesInFolder(String folderName, String ftpPath)

4、删除指定文件夹下的所有文件(包括子文件夹里面的文件,但由于不知怎么删除目录,所以暂没有做删除目录的功能) deleteAllFilesInFolder(String ftppath, String ftpdir)

5、删除指定文件 String deleteFile(String ftpPath)

6、判断FTP上目录是否存在 isDirExist(String dirname, String[] files)

7、上传单个文件 uploadFile(String clientFileName, String ftpPath)

8、下载单个文件 downloadFile(String remoteFileName,String localFileName)

9、删除指定文件夹下的所有文件(不包括子文件夹,只是删除指定文件夹下的文件)

三、实现过程

0、安装FTP服务器,配置域名、用户名、密码以及根目录

1、连接FTP服务器

/**************************************************************************

调用该构造函数的格式为:FtpService ftp=new FtpService("127.0.0.1","21","admin","admin");

打印效果如下则表示连接服务器成功

开始登录
登录成功
已转入根目录

**************************************************************************/

[java] view plaincopy
  1. /** 
  2.      * 初始化连接 
  3.      * @param pFtpServer FTP服务器地址 
  4.      * @param pFtpPort FTP服务器端口 
  5.      * @param pFtpUserName FTP登录用户名 
  6.      * @param pFtpPassword FTP登录密码 
  7.      * @throws IOException 
  8.     */   
  9.     public FtpService(String pFtpServer, String pFtpPort, String pFtpUserName,String pFtpPassword) throws Exception  
  10.     {  
  11.         this.ftpServer = pFtpServer;  
  12.           if (pFtpPort.trim().equals(""))  
  13.            this.ftpPort = "21";  
  14.           else  
  15.            this.ftpPort = pFtpPort;  
  16.           if (pFtpUserName.trim().equals(""))  
  17.            this.ftpUserName = "Anonymous";  
  18.           else  
  19.            this.ftpUserName = pFtpUserName;  
  20.           this.ftpPassword = pFtpPassword;  
  21.           try {     
  22.                     ftpClient = new FTPClient(); //ftpServer, Integer.parseInt(ftpPort)  
  23.                     ftpClient.setRemoteHost(ftpServer);  
  24.                     ftpClient.setRemotePort(Integer.parseInt(ftpPort));  
  25.                     ftpClient.setControlEncoding("gbk"); //加上这一句后在 edtftpj 2.0.1 下就可以传中文文件名了  
  26.                     System.out.println("开始登录");  
  27.                     ftpClient.connect();  
  28.                     ftpClient.login(ftpUserName, ftpPassword);  
  29.                     System.out.println("登录成功");  
  30.                     ftpClient.chdir("//"); //在有的ftp服务器运行会出错,用ftpClient.chdir("/")又可以了  
  31.                     System.out.println("已转入根目录");  
  32.                     isLogin = true;  
  33.           } catch (Exception e) {  
  34.            throw new Exception(e.getMessage());  
  35.           }  
  36.    }  

2、实现上传文件函数:上传指定文件夹下的所有文件到FTP指定目录下

[c-sharp] view plaincopy
  1. /** 
  2.      * 上传指定文件夹下的所有文件到FTP指定目录下 
  3.      * @param folderName 本地要上传的文件夹全路径 
  4.      * @param ftpPath FTP上对于根目录的路径 
  5.      * @throws IOException 
  6.     */      
  7.     public void uploadAllFilesInFolder(String folderName, String ftpPath) throws  
  8.             Exception {  
  9.         if (isLogin) {  
  10.             String strMsg = "";  
  11.             try {  
  12.                 File file = new File(folderName);  
  13.                 if (file.isDirectory()) {  
  14.                     ftpClient.chdir("//");  
  15.                     ftpClient.setType(FTPTransferType.BINARY);  
  16.                     if (checkFolderIsExist(ftpPath)) {  
  17.                         ftpClient.chdir(ftpPath);  
  18.                     } else {  
  19.                         createFolder(ftpPath);  
  20.                     }  
  21.                     File[] files = file.listFiles();  
  22.                     for (int i = 0; i < files.length; i++) {  
  23.                         if (files[i].isFile()) {  
  24.                             try {  
  25.                                 ftpClient.put(files[i].getPath(),  
  26.                                               files[i].getName());  
  27.                             } catch (Exception ee) {  
  28.                                 strMsg += "upload file<<:" + files[i].getPath() +  
  29.                                         ">> error!Message:" + ee.getMessage() +  
  30.                                         "/r/n";  
  31.                             }  
  32.                         }  
  33.                     }  
  34.                 } else {  
  35.                     throw new Exception(folderName + " is not a folder'name!");  
  36.                 }  
  37.             } catch (Exception e) {  
  38.                 throw new Exception(e.getMessage());  
  39.             }  
  40.         } else {  
  41.             throw new Exception("you didnot login remote ftp server!");  
  42.         }  
  43.     }  

3、实现上传单个文件函数

[java] view plaincopy
  1. /** 
  2.      * 上传单个文件 uploadFile(String clientFileName, String ftpPath) 
  3.      * @param clientFileName 本地要上传的文件的全路径 
  4.      * @param ftpPath FTP上对于根目录的路径 
  5.      * @throws IOException 
  6.     */  
  7.     public void uploadFile(String clientFileName, String ftpPath) throws  
  8.             Exception {  
  9.         if (isLogin) {  
  10.             try {  
  11.                 //获取文件名  
  12.                 String filename = "";  
  13.                 int index = clientFileName.lastIndexOf("//");  
  14.                 filename = clientFileName.substring(index + 1);  
  15.                 ftpClient.chdir("//");  
  16.                 ftpClient.setType(FTPTransferType.BINARY);  
  17.                 if (checkFolderIsExist(ftpPath)) {  
  18.                     ftpClient.chdir(ftpPath);  
  19.                 } else {  
  20.                     createFolder(ftpPath);  
  21.                 }  
  22.                 ftpClient.put(clientFileName, filename);  
  23.             } catch (Exception ex) {  
  24.                 throw new Exception(ex.getMessage());  
  25.             }  
  26.         } else {  
  27.             throw new Exception("you didnot login remote ftp server!");  
  28.         }  
  29.     }  

4、下载FTP服务器上指定的文件下的文件和子文件夹

[c-sharp] view plaincopy
  1. /** 
  2.      * 下载FTP服务器上指定的文件下的文件和子文件夹 
  3.      * @param ftpdir 服务器上要下载的文件夹,以根目录开始的相对路径(不含要下载的文件夹名) 
  4.      * @param outdir 要存放文件的本地目录 
  5.      * @param ftpdir 要下载的文件夹 
  6.      * @throws IOException 
  7.     */  
  8.     public void downloadFolder(String ftppath, String outdir, String ftpdir) throws  
  9.             IOException {  
  10.         try {  
  11.             ftppath = ftppath.replace('//''/');  
  12.             if (!ftppath.endsWith("/")) {  
  13.                 ftppath = ftppath + "/";  
  14.             }  
  15.             outdir = outdir.replace('//''/');  
  16.             if (!outdir.endsWith("/")) {  
  17.                 outdir = outdir + "/";  
  18.             }  
  19.             System.out.println("当前FTP路径:" + File.separator + ftppath + ftpdir);  
  20.             System.out.println("当前本地路径:" + outdir);  
  21.             ftpClient.chdir(File.separator + ftppath + ftpdir); //进入目录  
  22.             //ftpClient.chdir(ftppath); //进入指定目录  
  23.             //列出目录下所有文件和文件夹  
  24.             FTPFile[] ftpfiles = ftpClient.dirDetails("");  
  25.   
  26.             for (int i = 0; i < ftpfiles.length; i++) {  
  27.                 FTPFile ftpobj = ftpfiles[i];  
  28.                 // System.out.println("===================================");  
  29.                 //System.out.println("文件名:"+ftpobj.getName());  
  30.                 //System.out.println("路径:"+ftpobj.getPath());  
  31.                 //System.out.println("是否是止录:"+ftpobj.isDir());  
  32.                 //System.out.println("最后修改日录:"+ftpobj.lastModified());  
  33.                 //System.out.println("===================================");  
  34.                 if (!ftpobj.isDir()) { //是文件则直接下载文件  
  35.                     System.out.println("xiazaiwenjian:" + outdir +  
  36.                                        File.separator + ftpobj.getName());  
  37.                     // System.out.println("");  
  38.                     ftpClient.get(outdir + File.separator + ftpobj.getName(),  
  39.                                   ftpobj.getPath() + File.separator +  
  40.                                   ftpobj.getName());  
  41.                 } else {  
  42.                     createDirectory(outdir, ftpobj.getName());  
  43.                     System.out.println(ftpobj.getPath());  
  44.                     downloadFolder(ftppath,  
  45.                                    outdir + File.separator + ftpobj.getName(),  
  46.                                    ftpdir + File.separator + ftpobj.getName());  
  47.                 }  
  48.             }  
  49.         } catch (Exception e) {  
  50.             e.printStackTrace();  
  51.         }  
  52.     }  

5、下载单个文件

[java] view plaincopy
  1. /** 
  2.     *下载单个文件 downloadFile(String remoteFileName,String localFileName) 
  3.     * @param remoteFileName --服务器上的文件名(含全路径) 
  4.     * @param localFileName--本地文件名(全路径名) 
  5.     */  
  6.    public void downloadFile(String remoteFileName,String localFileName){  
  7.        try{  
  8.            ftpClient.get(localFileName, remoteFileName);  
  9.        }catch(Exception e){  
  10.            e.printStackTrace();  
  11.        }finally{  
  12.        }  
  13.    }  

6、删除指定文件

[java] view plaincopy
  1. /** 
  2.      * 删除指定文件 String deleteFile(String ftpPath) 
  3.      * @param ftpPath FTP上对于根目录的路径 
  4.      * @throws IOException 
  5.     */      
  6.     public String deleteFile(String ftpPath) throws  
  7.             Exception {  
  8.         if (isLogin) {  
  9.             String strMsg = "";  
  10.             try {  
  11.                 ftpClient.delete(ftpPath);  
  12.                 strMsg+="删除文件成功";  
  13.             } catch (FTPException ex) {  
  14.                 strMsg += "删除文件错误:" + ex.getMessage();  
  15.             } catch (IOException ex) {  
  16.                 strMsg += "操作文件错误:" + ex.getMessage();  
  17.             }  
  18.             return strMsg;  
  19.         } else {  
  20.             throw new Exception("you didnot login remote ftp server!");              
  21.         }  
  22.     }  

7、删除指定目录(包括文件夹本身)

[java] view plaincopy
  1. /** 
  2.      * 4、删除指定目录(包括文件夹本身)deleteFolder(String ftpPath) 
  3.      * @param ftpPath FTP上对于根目录的路径 
  4.      * @throws IOException 
  5.     */      
  6.     public String deleteFolder(String ftpPath) throws  
  7.             Exception {  
  8.         if (isLogin) {  
  9.             String strMsg = "";  
  10.             ftpClient.chdir("//"); //进入目录  
  11.             //列出目录下所有文件和文件夹  
  12.             FTPFile[] ftpfiles = ftpClient.dirDetails(ftpPath);  
  13.             for (int i = 0; i < ftpfiles.length; i++) {  
  14.                 FTPFile tempftpfile = ftpfiles[i];  
  15.                 System.out.println("===================================");  
  16.                 System.out.println("文件名:"+tempftpfile.getName());  
  17.                 System.out.println("路径:"+tempftpfile.getPath());  
  18.                 System.out.println("是否是止录:"+tempftpfile.isDir());  
  19.                 System.out.println("最后修改日录:"+tempftpfile.lastModified());  
  20.                 System.out.println("===================================");  
  21.   
  22.                 if (tempftpfile.isDir()) {  
  23.                     ftpPath = ftpPath + "//" + tempftpfile.getName();  
  24.                     System.out.println("1:" + ftpPath);  
  25.                     deleteFolder(ftpPath);  
  26.                 } else {  
  27.                     ftpClient.delete(ftpPath + "//" + tempftpfile.getName());  
  28.                 }  
  29.             }  
  30.          ftpClient.cdup();  
  31.             ftpClient.rmdir(ftpPath);              
  32.             return strMsg;  
  33.         } else {  
  34.             throw new Exception("you didnot login remote ftp server!");  
  35.         }  
  36.     }  

8、其他函数:判断文件夹、文件是否存在;创建文件夹或者文件

[java] view plaincopy
  1. /** 
  2.      * 判断文件夹是否存在,这种方式不是很准 
  3.      * @param dirname 要判断的目录名 
  4.      * @param files FTP上的文件列表 
  5.     */  
  6.     public static boolean isDirExist(String dirname, String[] files) {  
  7.         for (int i = 0; i < files.length; i++) {  
  8.             if (files[i].indexOf("<DIR>") > -1 &&  
  9.                 files[i].indexOf(dirname) > -1) {  
  10.                 return true;  
  11.             }  
  12.         }  
  13.         return false;  
  14.     }  
  15.       
  16.     /** 
  17.      * 在FTP服务上建立目录 
  18.      * @param directory FTP上对于根目录的路径 
  19.      * @param subDirectory 要在FTP上建立的目录 
  20.     */  
  21.     private static void createDirectory(String directory, String subDirectory) {  
  22.         String dir[];  
  23.         File fl = new File(directory);  
  24.         try {  
  25.             if (subDirectory == "" && fl.exists() != true) {  
  26.                 fl.mkdir();  
  27.             } else if (subDirectory != "") {  
  28.                 dir = subDirectory.replace('//''/').split("/");  
  29.                 for (int i = 0; i < dir.length; i++) {  
  30.                     File subFile = new File(directory + File.separator + dir[i]);  
  31.                     if (subFile.exists() == false) {  
  32.                         subFile.mkdir();  
  33.                     }  
  34.                     directory += File.separator + dir[i];  
  35.                 }  
  36.             }  
  37.         } catch (Exception ex) {  
  38.             System.out.println(ex.getMessage());  
  39.         }  
  40.     }  
  41.     /** 
  42.      * 检查FTP服务器上文件夹是否存在 
  43.      * @param pFolder FTP上对于根目录的路径 
  44.      * @throws Exception 
  45.     */  
  46.     public boolean checkFolderIsExist(String pFolder) throws Exception {  
  47.         if (isLogin) {  
  48.             String folder = pFolder.trim();  
  49.             if (folder.startsWith("//")) {  
  50.                 folder = folder.substring(1);  
  51.             }  
  52.             if (folder.endsWith("//")) {  
  53.                 folder = folder.substring(0, folder.length() - 1);  
  54.             }  
  55.             String strLayer = "..";  
  56.             if (folder.indexOf("//") > 0) {  
  57.                 String[] folders = folder.split("////");  
  58.                 for (int i = 1; i < folders.length; i++) {  
  59.                     strLayer += ",";  
  60.                     //System.out.println("strLayer:"+strLayer);  
  61.                 }  
  62.             }  
  63.             boolean result = false;  
  64.             try {  
  65.                 ftpClient.chdir(folder);  
  66.                 ftpClient.chdir(strLayer);  
  67.                 result = true;  
  68.             } catch (Exception ex) {  
  69.                 result = false;  
  70.             }  
  71.             return result;  
  72.         } else {  
  73.             throw new Exception("you didnot login remote ftp server!");  
  74.         }  
  75.     }  
  76.   
  77.     /** 
  78.      * 创建远程FTP服务器文件夹 
  79.      * @param pFolder FTP上对于根目录的路径 
  80.      * @throws Exception 
  81.     */  
  82.     public void createFolder(String pFolder) throws Exception {  
  83.         if (isLogin) {  
  84.             if (checkFolderIsExist(pFolder) == false) {  
  85.                 try {  
  86.                     String path = "";  
  87.                     ftpClient.chdir("//");  
  88.                     String[] folders = pFolder.split("////");  
  89.                     for (int i = 0; i < folders.length; i++) {  
  90.                         try {  
  91.                             ftpClient.chdir(folders[i]);  
  92.                         } catch (Exception ex) {  
  93.                             ftpClient.mkdir(folders[i]);  
  94.                             ftpClient.chdir(folders[i]);  
  95.                         }  
  96.                     }  
  97.                 } catch (Exception ex) {  
  98.                     throw new Exception(ex.getMessage());  
  99.                 }  
  100.             }  
  101.         } else {  
  102.             throw new Exception("you didnot login remote ftp server!");  
  103.         }  
  104.     }