1. 程式人生 > >【FTP】org.apache.commons.net.ftp.FTPClient實現復雜的上傳下載,操作目錄,處理編碼

【FTP】org.apache.commons.net.ftp.FTPClient實現復雜的上傳下載,操作目錄,處理編碼

ttr hide working log 登錄 有一個 ima spl att

和上一份簡單 上傳下載一樣

來,任何的方法不懂的,http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html

API拿走不謝!!!

1.FTP配置實體

技術分享
 1 package com.agen.util;
 2 
 3 public class FtpConfig {
 4      //主機ip  
 5     private String FtpHost = "192.168.18.252";  
 6     //端口號  
 7     private int FtpPort = 21;  
8 //ftp用戶名 9 private String FtpUser = "ftp"; 10 //ftp密碼 11 private String FtpPassword = "agenbiology"; 12 //ftp中的目錄 這裏先指定的根目錄 13 private String FtpPath = "/"; 14 15 16 17 public String getFtpHost() { 18 return FtpHost; 19 } 20 public void setFtpHost(String ftpHost) {
21 FtpHost = ftpHost; 22 } 23 public int getFtpPort() { 24 return FtpPort; 25 } 26 public void setFtpPort(int ftpPort) { 27 FtpPort = ftpPort; 28 } 29 public String getFtpUser() { 30 return FtpUser; 31 } 32 public void setFtpUser(String ftpUser) {
33 FtpUser = ftpUser; 34 } 35 public String getFtpPassword() { 36 return FtpPassword; 37 } 38 public void setFtpPassword(String ftpPassword) { 39 FtpPassword = ftpPassword; 40 } 41 public String getFtpPath() { 42 return FtpPath; 43 } 44 public void setFtpPath(String ftpPath) { 45 FtpPath = ftpPath; 46 } 47 48 49 50 }
View Code

2.FTP工具類,僅有一個刪除文件夾【目錄】的操作方法,刪除文件夾包括文件夾下所有的文件

技術分享
  1 package com.agen.util;
  2 
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.io.OutputStream;
  6 
  7 import org.apache.commons.net.ftp.FTPClient;
  8 import org.apache.commons.net.ftp.FTPFile;
  9 
 10 
 11 
 12 public class FtpUtils {
 13     
 14     /**
 15      * 獲取FTP連接
 16      * @return
 17      */
 18     public  FTPClient getFTPClient() {
 19         FtpConfig config = new FtpConfig();
 20         FTPClient ftpClient = new FTPClient();
 21         boolean result = true;
 22         try {
 23             //連接FTP服務器
 24             ftpClient.connect(config.getFtpHost(), config.getFtpPort());
 25             //如果連接
 26             if (ftpClient.isConnected()) {
 27                 //提供用戶名/密碼登錄FTP服務器
 28                 boolean flag = ftpClient.login(config.getFtpUser(), config.getFtpPassword());
 29                 //如果登錄成功
 30                 if (flag) {
 31                     //設置編碼類型為UTF-8
 32                     ftpClient.setControlEncoding("UTF-8");
 33                     //設置文件類型為二進制文件類型
 34                     ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
 35                 } else {
 36                     result = false;
 37                 }
 38             } else {
 39                 result = false;
 40             }
 41             //成功連接並 登陸成功  返回連接
 42             if (result) {
 43                 return ftpClient;
 44             } else {
 45                 return null;
 46             }
 47         } catch (Exception e) {
 48             e.printStackTrace();
 49             return null;
 50         }
 51     }
 52     /**
 53      * 刪除文件夾下所有文件
 54      * @return
 55      * @throws IOException 
 56      */
 57     public boolean deleteFiles(String pathname) throws IOException{
 58         FTPClient ftpClient = getFTPClient();
 59         FTPFile [] ftpFiles = ftpClient.listFiles(new String((pathname).getBytes("UTF-8"),"iso-8859-1"));
 60         if(ftpFiles.length > 0){
 61             for (int i = 0; i < ftpFiles.length; i++) {
 62                 System.out.println(ftpFiles[i].getName());
 63                 if(ftpFiles[i].isDirectory()){
 64                     deleteFiles(pathname+"/"+ftpFiles[i].getName());
 65                 }else{
 66                     System.out.println(pathname);
 67                     //這裏需要提供刪除文件的路徑名 才能刪除文件
 68                     ftpClient.deleteFile(new String((pathname+"/"+ftpFiles[i].getName()).getBytes("UTF-8"),"iso-8859-1"));
 69                     FTPFile [] ftFiles = ftpClient.listFiles(new String((pathname).getBytes("UTF-8"),"iso-8859-1"));
 70                     if(ftFiles.length == 0){//如果文件夾中現在已經為空了
 71                         ftpClient.removeDirectory(new String(pathname.getBytes("UTF-8"),"iso-8859-1"));
 72                     }
 73                 }
 74             }
 75         }
 76         return true;
 77     }
 78     
 79     /**
 80      * 關閉 輸入流或輸出流
 81      * @param in
 82      * @param out
 83      * @param ftpClient
 84      */
 85     public  void close(InputStream in, OutputStream out,FTPClient ftpClient) {
 86         if (null != in) {
 87             try {
 88                 in.close();
 89             } catch (IOException e) {
 90                 e.printStackTrace();
 91                 System.out.println("輸入流關閉失敗");
 92             }
 93         }
 94         if (null != out) {
 95             try {
 96                 out.close();
 97             } catch (IOException e) {
 98                 e.printStackTrace();
 99                 System.out.println("輸出流關閉失敗");
100             }
101         }
102         if (null != ftpClient) {
103             try {
104                 ftpClient.logout();
105                 ftpClient.disconnect();
106             } catch (IOException e) {
107                 e.printStackTrace();
108                 System.out.println("Ftp服務關閉失敗!");
109             }
110         }
111     }
112     
113 }
View Code

3.實際用到的FTP上傳【創建多層中文目錄】+下載【瀏覽器下載OR服務器下載】+刪除 【處理FTP編碼方式與本地編碼不一致】

技術分享
  1 /**
  2      * 上傳至FTP服務器
  3      * @param partFile
  4      * @param request
  5      * @param diseaseName
  6      * @param productName
  7      * @param diseaseId
  8      * @return
  9      * @throws IOException
 10      */
 11     @RequestMapping("/uploadFiles")
 12     @ResponseBody
 13     public  boolean uploadFiles(@RequestParam("upfile")MultipartFile partFile,HttpServletRequest request,String diseaseName,String productName,String diseaseId) throws IOException{
 14              Disease disease = new Disease();
 15              disease.setDiseaseId(diseaseId);  
 16              Criteria criteria = getCurrentSession().createCriteria(Filelist.class);
 17              criteria.add(Restrictions.eq("disease", disease));
 18              Filelist flFilelist = filelistService.uniqueResult(criteria);
 19              if(flFilelist == null){
 20                  FtpUtils ftpUtils = new FtpUtils();
 21                  boolean result = true;
 22                 InputStream in = null;
 23                 FTPClient ftpClient = ftpUtils.getFTPClient();
 24                 if (null == ftpClient) {
 25                     System.out.println("FTP服務器未連接成功!!!");
 26                     return false;
 27                 }
 28                 try {
 29                     
 30                     String path = "/file-ave/";
 31                     ftpClient.changeWorkingDirectory(path);
 32                     System.out.println(ftpClient.printWorkingDirectory());
 33                     //創建產品文件夾   轉碼 防止在FTP服務器上創建時亂碼
 34                     ftpClient.makeDirectory(new String(productName.getBytes("UTF-8"),"iso-8859-1"));
 35                     //指定當前的工作路徑到產品文件夾下
 36                     ftpClient.changeWorkingDirectory(path+new String(productName.getBytes("UTF-8"),"iso-8859-1"));
 37                     //創建疾病文件夾   轉碼
 38                     ftpClient.makeDirectory(new String(diseaseName.getBytes("UTF-8"),"iso-8859-1"));
 39                     //指定當前的工作路徑到疾病文件夾下
 40                     ftpClient.changeWorkingDirectory(path+new String(productName.getBytes("UTF-8"),"iso-8859-1")+"/"+new String(diseaseName.getBytes("UTF-8"),"iso-8859-1"));
 41                     
 42                     // 得到上傳的文件的文件名
 43                     String filename = partFile.getOriginalFilename();
 44                     in = partFile.getInputStream();
 45                     ftpClient.storeFile(new String(filename.getBytes("UTF-8"),"iso-8859-1"), in);
 46                     path += productName+"/"+diseaseName+"/";
 47                     
 48                     
 49                     DecimalFormat df = new DecimalFormat();
 50                       String fileSize = partFile.getSize()/1024>100 ? (partFile.getSize()/1024/1024>100? df.format((double)partFile.getSize()/1024/1024/1024)+"GB" :df.format((double)partFile.getSize()/1024/1024)+"MB" ) :df.format((double)partFile.getSize()/1024)+"KB";
 51                       HttpSession session = request.getSession();
 52                       User user = (User) session.getAttribute("user");
 53                      
 54                       Filelist filelist = new Filelist();
 55                       filelist.setFileId(UUID.randomUUID().toString());
 56                       filelist.setFileName(filename);
 57                       filelist.setFilePath(path+filename);
 58                       filelist.setFileCre(fileSize);
 59                       filelist.setCreateDate(new Timestamp(System.currentTimeMillis()));
 60                       filelist.setUpdateDate(new Timestamp(System.currentTimeMillis()));
 61                       filelist.setTransPerson(user.getUserId());
 62                       filelist.setDisease(disease);
 63                       filelistService.save(filelist);
 64                       
 65                     
 66                     
 67                     return result;
 68                     
 69                 } catch (IOException e) {
 70                     e.printStackTrace();
 71                     return false;
 72                 } finally {
 73                     ftpUtils.close(in, null, ftpClient);
 74                 }
 75              }else{
 76                  return false;
 77              }
 78     }
 79     
 80     /**
 81      * 刪除文件
 82      * @param filelistId
 83      * @return
 84      * @throws IOException 
 85      * @throws UnsupportedEncodingException 
 86      */
 87     @RequestMapping("/filelistDelete")
 88     @ResponseBody
 89       public boolean filelistDelete(String []filelistId) throws UnsupportedEncodingException, IOException{
 90         for (String string : filelistId) {
 91             Filelist filelist =  filelistService.uniqueResult("fileId", string);
 92             String filePath = filelist.getFilePath();
 93             FtpUtils ftpUtils = new FtpUtils();
 94             FTPClient ftpClient = ftpUtils.getFTPClient();
 95             InputStream inputStream = ftpClient.retrieveFileStream(new String(filePath.getBytes("UTF-8"),"iso-8859-1"));
 96             if(inputStream != null || ftpClient.getReplyCode() == 550){
 97                 ftpClient.deleteFile(new String(filePath.getBytes("UTF-8"),"iso-8859-1"));
 98             }
 99             filelistService.deleteById(string);
100         }
101         return true;
102       }
103     
104     /**
105      * 下載到本地
106      * @param fileId
107      * @param response
108      * @return
109      * @throws IOException
110      * @throws InterruptedException
111      */
112     @RequestMapping("/fileDownload")
113     public String fileDownload(String fileId,HttpServletResponse response) throws IOException, InterruptedException{
114         Filelist filelist = filelistService.get(fileId);
115         Assert.notNull(filelist);
116         String filePath = filelist.getFilePath();
117         String fileName = filelist.getFileName();
118         String targetPath = "D:/biologyInfo/Download/";
119         File file = new File(targetPath);
120         while(!file.exists()){
121             file.mkdirs();
122         }
123         FtpUtils ftpUtils = new FtpUtils(); 
124         FileOutputStream out = null;
125         FTPClient ftpClient = ftpUtils.getFTPClient();
126         if (null == ftpClient) {
127             System.out.println("FTP服務器未連接成功!!!");
128         }
129         try {
130             //下載到 應用服務器而不是本地
131 //            //要寫到本地的位置
132 //            File file2 = new File(targetPath + fileName);
133 //            out = new FileOutputStream(file2);
134 //            //截取文件的存儲位置 不包括文件本身
135 //            filePath = filePath.substring(0, filePath.lastIndexOf("/"));
136 //            //文件存儲在FTP的位置
137 //            ftpClient.changeWorkingDirectory(new String(filePath.getBytes("UTF-8"),"iso-8859-1"));
138 //            System.out.println(ftpClient.printWorkingDirectory());
139 //            //下載文件
140 //            ftpClient.retrieveFile(new String(fileName.getBytes("UTF-8"),"iso-8859-1"), out);
141 //            return true;
142             
143             //下載到  客戶端 瀏覽器
144             InputStream inputStream = ftpClient.retrieveFileStream(new String(filePath.getBytes("UTF-8"),"iso-8859-1"));
145             response.setContentType("multipart/form-data");
146             response.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("UTF-8"),"iso-8859-1")); 
147             OutputStream outputStream = response.getOutputStream();
148              byte[] b = new byte[1024];  
149              int length = 0;  
150              while ((length = inputStream.read(b)) != -1) {  
151                 outputStream.write(b, 0, length);  
152              }
153              
154         } catch (IOException e) {
155             e.printStackTrace();
156         } finally {
157             ftpUtils.close(null, out, ftpClient);
158         }
159         return null;
160     }
View Code

【FTP】org.apache.commons.net.ftp.FTPClient實現復雜的上傳下載,操作目錄,處理編碼