码迷,mamicode.com
首页 > Web开发 > 详细

【FTP】org.apache.commons.net.ftp.FTPClient实现复杂的上传下载,操作目录,处理编码

时间:2017-06-30 12:26:05      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:uuid   inf   play   attach   ssi   []   pack   bio   product   

和上一份简单 上传下载一样

来,任何的方法不懂的,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实现复杂的上传下载,操作目录,处理编码

标签:uuid   inf   play   attach   ssi   []   pack   bio   product   

原文地址:http://www.cnblogs.com/sxdcgaq8080/p/7098073.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!