時間: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");
列印效果如下則表示串連伺服器成功
開始登入
登入成功
已轉入根目錄
**************************************************************************/
/**<br /> * 初始化串連<br /> * @param pFtpServer FTP伺服器位址<br /> * @param pFtpPort FTP伺服器連接埠<br /> * @param pFtpUserName FTP登入使用者名稱<br /> * @param pFtpPassword FTP登入密碼<br /> * @throws IOException<br /> */<br /> public FtpService(String pFtpServer, String pFtpPort, String pFtpUserName,String pFtpPassword) throws Exception<br /> {<br /> this.ftpServer = pFtpServer;<br /> if (pFtpPort.trim().equals(""))<br /> this.ftpPort = "21";<br /> else<br /> this.ftpPort = pFtpPort;<br /> if (pFtpUserName.trim().equals(""))<br /> this.ftpUserName = "Anonymous";<br /> else<br /> this.ftpUserName = pFtpUserName;<br /> this.ftpPassword = pFtpPassword;<br /> try {<br /> ftpClient = new FTPClient(); //ftpServer, Integer.parseInt(ftpPort)<br /> ftpClient.setRemoteHost(ftpServer);<br /> ftpClient.setRemotePort(Integer.parseInt(ftpPort));<br /> ftpClient.setControlEncoding("gbk"); //加上這一句後在 edtftpj 2.0.1 下就可以傳中文檔案名稱了<br /> System.out.println("開始登入");<br /> ftpClient.connect();<br /> ftpClient.login(ftpUserName, ftpPassword);<br /> System.out.println("登入成功");<br /> ftpClient.chdir("//"); //在有的ftp伺服器運行會出錯,用ftpClient.chdir("/")又可以了<br /> System.out.println("已轉入根目錄");<br /> isLogin = true;<br /> } catch (Exception e) {<br /> throw new Exception(e.getMessage());<br /> }<br /> }
2、實現上傳檔案函數:上傳指定檔案夾下的所有檔案到FTP指定目錄下
/**<br /> * 上傳指定檔案夾下的所有檔案到FTP指定目錄下<br /> * @param folderName 本地要上傳的檔案夾全路徑<br /> * @param ftpPath FTP上對於根目錄的路徑<br /> * @throws IOException<br /> */<br /> public void uploadAllFilesInFolder(String folderName, String ftpPath) throws<br /> Exception {<br /> if (isLogin) {<br /> String strMsg = "";<br /> try {<br /> File file = new File(folderName);<br /> if (file.isDirectory()) {<br /> ftpClient.chdir("//");<br /> ftpClient.setType(FTPTransferType.BINARY);<br /> if (checkFolderIsExist(ftpPath)) {<br /> ftpClient.chdir(ftpPath);<br /> } else {<br /> createFolder(ftpPath);<br /> }<br /> File[] files = file.listFiles();<br /> for (int i = 0; i < files.length; i++) {<br /> if (files[i].isFile()) {<br /> try {<br /> ftpClient.put(files[i].getPath(),<br /> files[i].getName());<br /> } catch (Exception ee) {<br /> strMsg += "upload file<<:" + files[i].getPath() +<br /> ">> error!Message:" + ee.getMessage() +<br /> "/r/n";<br /> }<br /> }<br /> }<br /> } else {<br /> throw new Exception(folderName + " is not a folder'name!");<br /> }<br /> } catch (Exception e) {<br /> throw new Exception(e.getMessage());<br /> }<br /> } else {<br /> throw new Exception("you didnot login remote ftp server!");<br /> }<br /> }<br />
3、實現上傳單個檔案函數
/**<br /> * 上傳單個檔案 uploadFile(String clientFileName, String ftpPath)<br /> * @param clientFileName 本地要上傳的檔案的全路徑<br /> * @param ftpPath FTP上對於根目錄的路徑<br /> * @throws IOException<br /> */<br /> public void uploadFile(String clientFileName, String ftpPath) throws<br /> Exception {<br /> if (isLogin) {<br /> try {<br /> //擷取檔案名稱<br /> String filename = "";<br /> int index = clientFileName.lastIndexOf("//");<br /> filename = clientFileName.substring(index + 1);<br /> ftpClient.chdir("//");<br /> ftpClient.setType(FTPTransferType.BINARY);<br /> if (checkFolderIsExist(ftpPath)) {<br /> ftpClient.chdir(ftpPath);<br /> } else {<br /> createFolder(ftpPath);<br /> }<br /> ftpClient.put(clientFileName, filename);<br /> } catch (Exception ex) {<br /> throw new Exception(ex.getMessage());<br /> }<br /> } else {<br /> throw new Exception("you didnot login remote ftp server!");<br /> }<br /> }<br />
4、下載FTP伺服器上指定的檔案下的檔案和子檔案夾
/**<br /> * 下載FTP伺服器上指定的檔案下的檔案和子檔案夾<br /> * @param ftpdir 伺服器上要下載的檔案夾,以根目錄開始的相對路徑(不含要下載的檔案夾名)<br /> * @param outdir 要存放檔案的本地目錄<br /> * @param ftpdir 要下載的檔案夾<br /> * @throws IOException<br /> */<br /> public void downloadFolder(String ftppath, String outdir, String ftpdir) throws<br /> IOException {<br /> try {<br /> ftppath = ftppath.replace('//', '/');<br /> if (!ftppath.endsWith("/")) {<br /> ftppath = ftppath + "/";<br /> }<br /> outdir = outdir.replace('//', '/');<br /> if (!outdir.endsWith("/")) {<br /> outdir = outdir + "/";<br /> }<br /> System.out.println("當前FTP路徑:" + File.separator + ftppath + ftpdir);<br /> System.out.println("當前本地路徑:" + outdir);<br /> ftpClient.chdir(File.separator + ftppath + ftpdir); //進入目錄<br /> //ftpClient.chdir(ftppath); //進入指定目錄<br /> //列出目錄下所有檔案和檔案夾<br /> FTPFile[] ftpfiles = ftpClient.dirDetails("");</p><p> for (int i = 0; i < ftpfiles.length; i++) {<br /> FTPFile ftpobj = ftpfiles[i];<br /> // System.out.println("===================================");<br /> //System.out.println("檔案名稱:"+ftpobj.getName());<br /> //System.out.println("路徑:"+ftpobj.getPath());<br /> //System.out.println("是否是止錄:"+ftpobj.isDir());<br /> //System.out.println("最後修改日錄:"+ftpobj.lastModified());<br /> //System.out.println("===================================");<br /> if (!ftpobj.isDir()) { //是檔案則直接下載檔案<br /> System.out.println("xiazaiwenjian:" + outdir +<br /> File.separator + ftpobj.getName());<br /> // System.out.println("");<br /> ftpClient.get(outdir + File.separator + ftpobj.getName(),<br /> ftpobj.getPath() + File.separator +<br /> ftpobj.getName());<br /> } else {<br /> createDirectory(outdir, ftpobj.getName());<br /> System.out.println(ftpobj.getPath());<br /> downloadFolder(ftppath,<br /> outdir + File.separator + ftpobj.getName(),<br /> ftpdir + File.separator + ftpobj.getName());<br /> }<br /> }<br /> } catch (Exception e) {<br /> e.printStackTrace();<br /> }<br /> }</p><p>
5、下載單個檔案
/**<br /> *下載單個檔案 downloadFile(String remoteFileName,String localFileName)<br /> * @param remoteFileName --伺服器上的檔案名稱(含全路徑)<br /> * @param localFileName--本地檔案名稱(全路徑名)<br /> */<br /> public void downloadFile(String remoteFileName,String localFileName){<br /> try{<br /> ftpClient.get(localFileName, remoteFileName);<br /> }catch(Exception e){<br /> e.printStackTrace();<br /> }finally{<br /> }<br /> }
6、刪除指定檔案
/**<br /> * 刪除指定檔案 String deleteFile(String ftpPath)<br /> * @param ftpPath FTP上對於根目錄的路徑<br /> * @throws IOException<br /> */<br /> public String deleteFile(String ftpPath) throws<br /> Exception {<br /> if (isLogin) {<br /> String strMsg = "";<br /> try {<br /> ftpClient.delete(ftpPath);<br /> strMsg+="刪除檔案成功";<br /> } catch (FTPException ex) {<br /> strMsg += "刪除檔案錯誤:" + ex.getMessage();<br /> } catch (IOException ex) {<br /> strMsg += "操作檔案錯誤:" + ex.getMessage();<br /> }<br /> return strMsg;<br /> } else {<br /> throw new Exception("you didnot login remote ftp server!");<br /> }<br /> }
7、刪除指定目錄(包括檔案夾本身)
/**<br /> * 4、刪除指定目錄(包括檔案夾本身)deleteFolder(String ftpPath)<br /> * @param ftpPath FTP上對於根目錄的路徑<br /> * @throws IOException<br /> */<br /> public String deleteFolder(String ftpPath) throws<br /> Exception {<br /> if (isLogin) {<br /> String strMsg = "";<br /> ftpClient.chdir("//"); //進入目錄<br /> //列出目錄下所有檔案和檔案夾<br /> FTPFile[] ftpfiles = ftpClient.dirDetails(ftpPath);<br /> for (int i = 0; i < ftpfiles.length; i++) {<br /> FTPFile tempftpfile = ftpfiles[i];<br /> System.out.println("===================================");<br /> System.out.println("檔案名稱:"+tempftpfile.getName());<br /> System.out.println("路徑:"+tempftpfile.getPath());<br /> System.out.println("是否是止錄:"+tempftpfile.isDir());<br /> System.out.println("最後修改日錄:"+tempftpfile.lastModified());<br /> System.out.println("===================================");</p><p> if (tempftpfile.isDir()) {<br /> ftpPath = ftpPath + "//" + tempftpfile.getName();<br /> System.out.println("1:" + ftpPath);<br /> deleteFolder(ftpPath);<br /> } else {<br /> ftpClient.delete(ftpPath + "//" + tempftpfile.getName());<br /> }<br /> }<br /> ftpClient.cdup();<br /> ftpClient.rmdir(ftpPath);<br /> return strMsg;<br /> } else {<br /> throw new Exception("you didnot login remote ftp server!");<br /> }<br /> }
8、其他函數:判斷檔案夾、檔案是否存在;建立檔案夾或者檔案
/**<br /> * 判斷檔案夾是否存在,這種方式不是很准<br /> * @param dirname 要判斷的目錄名<br /> * @param files FTP上的檔案清單<br /> */<br /> public static boolean isDirExist(String dirname, String[] files) {<br /> for (int i = 0; i < files.length; i++) {<br /> if (files[i].indexOf("<DIR>") > -1 &&<br /> files[i].indexOf(dirname) > -1) {<br /> return true;<br /> }<br /> }<br /> return false;<br /> }</p><p> /**<br /> * 在FTP服務上建立目錄<br /> * @param directory FTP上對於根目錄的路徑<br /> * @param subDirectory 要在FTP上建立的目錄<br /> */<br /> private static void createDirectory(String directory, String subDirectory) {<br /> String dir[];<br /> File fl = new File(directory);<br /> try {<br /> if (subDirectory == "" && fl.exists() != true) {<br /> fl.mkdir();<br /> } else if (subDirectory != "") {<br /> dir = subDirectory.replace('//', '/').split("/");<br /> for (int i = 0; i < dir.length; i++) {<br /> File subFile = new File(directory + File.separator + dir[i]);<br /> if (subFile.exists() == false) {<br /> subFile.mkdir();<br /> }<br /> directory += File.separator + dir[i];<br /> }<br /> }<br /> } catch (Exception ex) {<br /> System.out.println(ex.getMessage());<br /> }<br /> }<br /> /**<br /> * 檢查FTP伺服器上檔案夾是否存在<br /> * @param pFolder FTP上對於根目錄的路徑<br /> * @throws Exception<br /> */<br /> public boolean checkFolderIsExist(String pFolder) throws Exception {<br /> if (isLogin) {<br /> String folder = pFolder.trim();<br /> if (folder.startsWith("//")) {<br /> folder = folder.substring(1);<br /> }<br /> if (folder.endsWith("//")) {<br /> folder = folder.substring(0, folder.length() - 1);<br /> }<br /> String strLayer = "..";<br /> if (folder.indexOf("//") > 0) {<br /> String[] folders = folder.split("////");<br /> for (int i = 1; i < folders.length; i++) {<br /> strLayer += ",";<br /> //System.out.println("strLayer:"+strLayer);<br /> }<br /> }<br /> boolean result = false;<br /> try {<br /> ftpClient.chdir(folder);<br /> ftpClient.chdir(strLayer);<br /> result = true;<br /> } catch (Exception ex) {<br /> result = false;<br /> }<br /> return result;<br /> } else {<br /> throw new Exception("you didnot login remote ftp server!");<br /> }<br /> }</p><p> /**<br /> * 建立遠程FTP伺服器檔案夾<br /> * @param pFolder FTP上對於根目錄的路徑<br /> * @throws Exception<br /> */<br /> public void createFolder(String pFolder) throws Exception {<br /> if (isLogin) {<br /> if (checkFolderIsExist(pFolder) == false) {<br /> try {<br /> String path = "";<br /> ftpClient.chdir("//");<br /> String[] folders = pFolder.split("////");<br /> for (int i = 0; i < folders.length; i++) {<br /> try {<br /> ftpClient.chdir(folders[i]);<br /> } catch (Exception ex) {<br /> ftpClient.mkdir(folders[i]);<br /> ftpClient.chdir(folders[i]);<br /> }<br /> }<br /> } catch (Exception ex) {<br /> throw new Exception(ex.getMessage());<br /> }<br /> }<br /> } else {<br /> throw new Exception("you didnot login remote ftp server!");<br /> }<br /> }