struts2 上傳文件 FtpClient ftp操作

網上很多介紹struts2 上傳文件的例子,但很多都忘記了說明要加上攔截器fileUploadStack,否則得到的file將會是空的,以下是項目中用到的代碼,同時涉及到ftp操作

Action類


  1. /**

  2. * ViewAction.java

  3. * com.sword.actions

  4. *

  5. * Function: TODO

  6. *

  7. *   ver     date           author

  8. * ──────────────────────────────────

  9. *           2010-7-1       lidl

  10. *

  11. * Copyright (c) 2010, TNT All Rights Reserved.

  12. */

  13. package com.sword.actions;  

  14. import java.io.File;  

  15. import java.io.IOException;  

  16. import java.text.DateFormat;  

  17. import java.text.SimpleDateFormat;  

  18. import java.util.Date;  

  19. import java.util.Random;  

  20. import org.apache.commons.io.FileUtils;  

  21. import org.apache.struts2.ServletActionContext;  

  22. import org.apache.struts2.convention.annotation.Action;  

  23. import org.apache.struts2.convention.annotation.InterceptorRef;  

  24. import com.opensymphony.xwork2.ActionSupport;  

  25. import com.sword.util.FtpUtil;  

  26. import com.webservice.SingleMap;  

  27. /**

  28. * ClassName:ViewAction

  29. * Function: TODO ADD FUNCTION

  30. * Reason:   TODO ADD REASON

  31. *

  32. * @author   lidl

  33. * @version  

  34. * @since    Ver 1.1

  35. * @Date     2010-7-1       下午05:54:31

  36. *

  37. * @see      

  38. */

  39. publicclass ViewAction extends ActionSupport{  

  40. privateint validateNum;  

  41. private File attachment;  

  42. private String attachmentFileName;  

  43. private String attachmentContentType;  

  44. @Action(interceptorRefs=@InterceptorRef("fileUploadStack"))  

  45. public String execute(){  

  46.        SingleMap map = SingleMap.getInstance();  

  47. int num_int=((Integer)map.map.get("login")).intValue();  

  48.        System.out.println("num_int:"+num_int+",validateNum:"+validateNum+"->"+(num_int==validateNum));  

  49.        System.out.println("size:" + map.map.size());  

  50.        map.map.remove("login");  

  51. if(num_int==validateNum){  

  52.            System.out.println(attachment == null);  

  53.            String targetDirectory = ServletActionContext.getServletContext()  

  54.                    .getRealPath("/temp");  

  55.            String targetFileName = generateFileName(attachmentFileName);  

  56.            File target = new File(targetDirectory, targetFileName);  

  57.            targetDirectory+="/"+targetFileName;  

  58. try {  

  59.                FileUtils.copyFile(attachment, target);  

  60.            } catch (IOException e) {  

  61. // TODO Auto-generated catch block

  62.                e.printStackTrace();  

  63.            }finally{  

  64.                System.out.println(targetDirectory);  

  65.                FtpUtil ftp=new FtpUtil();  

  66. try {  

  67.                    ftp.connectServer("192.168.32.130", "lidl", "aall", "/ftp");  

  68.                    System.out.println("filesize:"

  69.                            + ftp.upload(targetDirectory) + "字節");  

  70.                } catch (IOException e) {  

  71. // TODO Auto-generated catch block

  72.                    e.printStackTrace();  

  73.                } catch (Exception e) {  

  74. // TODO Auto-generated catch block

  75.                    e.printStackTrace();  

  76.                }finally{  

  77. try {  

  78.                        ftp.closeServer();  

  79.                    } catch (IOException e) {  

  80. // TODO Auto-generated catch block

  81.                        e.printStackTrace();  

  82.                    }  

  83.                }  

  84.            }  

  85. return"success";  

  86.        }else{  

  87. return"error";  

  88.        }  

  89.    }  

  90. private String generateFileName(String fileName) {    

  91.             DateFormat format = new SimpleDateFormat("yyMMddHHmmss");    

  92.             String formatDate = format.format(new Date());    

  93. int random = new Random().nextInt(10000);    

  94. int position = fileName.lastIndexOf(".");    

  95.             String extension = fileName.substring(position);    

  96. return formatDate + random + extension;    

  97.         }  

  98. publicint getValidateNum() {  

  99. return validateNum;  

  100.    }  

  101. publicvoid setValidateNum(int validateNum) {  

  102. this.validateNum = validateNum;  

  103.    }  

  104. public File getAttachment() {  

  105. return attachment;  

  106.    }  

  107. publicvoid setAttachment(File attachment) {  

  108. this.attachment = attachment;  

  109.    }  

  110. public String getAttachmentFileName() {  

  111. return attachmentFileName;  

  112.    }  

  113. publicvoid setAttachmentFileName(String attachmentFileName) {  

  114. this.attachmentFileName = attachmentFileName;  

  115.    }  

  116. public String getAttachmentContentType() {  

  117. return attachmentContentType;  

  118.    }  

  119. publicvoid setAttachmentContentType(String attachmentContentType) {  

  120. this.attachmentContentType = attachmentContentType;  

  121.    }  

  122. }  


(文件上傳 ,請在struts.xml裏配上  <constant name="struts.multipart.saveDir" value="/tmp"/> 用來保存臨時文件,同時爲了 讓系統清除臨時文件 請在web.xml裏配上 )

web.xml


  1. <filter>    

  2.       <filter-name>struts-cleanup</filter-name>    

  3.       <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>    

  4.   </filter>    

  5. <filter>  

  6.  <filter-name>struts2</filter-name>  

  7.  <filter-class>    

  8.           com.sword.actions.FilterDispetor    

  9.  </filter-class>  

  10. </filter>  

  11.    <filter-mapping>    

  12.       <filter-name>struts-cleanup</filter-name>    

  13.       <url-pattern>/*</url-pattern>    

  14.   </filter-mapping>    

  15. <filter-mapping>  

  16.  <filter-name>struts2</filter-name>  

  17.  <url-pattern>/*</url-pattern>  

  18. </filter-mapping>  



ftp 操作類


  1. package com.sword.util;  

  2. import java.io.DataInputStream;  

  3. import java.io.FileInputStream;  

  4. import java.io.FileOutputStream;  

  5. import java.io.IOException;  

  6. import java.util.ArrayList;  

  7. import java.util.List;  

  8. import sun.net.TelnetInputStream;  

  9. import sun.net.TelnetOutputStream;  

  10. import sun.net.ftp.FtpClient;  

  11. publicclass FtpUtil {  

  12. private FtpClient ftpClient;  

  13. /**

  14.     * connectServer 連接ftp服務器

  15.     *

  16.     * @throws java.io.IOException

  17.     * @param path

  18.     *            文件夾,空代表根目錄

  19.     * @param password

  20.     *            密碼

  21.     * @param user

  22.     *            登陸用戶

  23.     * @param server

  24.     *            服務器地址

  25.     */

  26. publicvoid connectServer(String server, String user, String password,  

  27.            String path) throws IOException {  

  28. // server:FTP服務器的IP地址;user:登錄FTP服務器的用戶名

  29. // password:登錄FTP服務器的用戶名的口令;path:FTP服務器上的路徑

  30.        ftpClient = new FtpClient();  

  31.        ftpClient.openServer(server);  

  32.        ftpClient.login(user, password);  

  33. // path是ftp服務下主目錄的子目錄

  34. if (path.length() != 0)  

  35.            ftpClient.cd(path);  

  36. // 用2進制上傳、下載

  37.        ftpClient.binary();  

  38.    }  

  39. /**

  40.     * upload 上傳文件

  41.     *

  42.     * @throws java.lang.Exception

  43.     * @return -1 文件不存在 -2 文件內容爲空 >0 成功上傳,返回文件的大小

  44.     * @param newname

  45.     *            上傳後的新文件名

  46.     * @param filename

  47.     *            上傳的文件

  48.     */

  49. publiclong upload(String filename, String newname) throws Exception {  

  50. long result = 0;  

  51.        TelnetOutputStream os = null;  

  52.        FileInputStream is = null;  

  53. try {  

  54.            java.io.File file_in = new java.io.File(filename);  

  55. if (!file_in.exists())  

  56. return -1;  

  57. if (file_in.length() == 0)  

  58. return -2;  

  59.            os = ftpClient.put(newname);  

  60.            result = file_in.length();  

  61.            is = new FileInputStream(file_in);  

  62. byte[] bytes = newbyte[1024];  

  63. int c;  

  64. while ((c = is.read(bytes)) != -1) {  

  65.                os.write(bytes, 0, c);  

  66.            }  

  67.        } finally {  

  68. if (is != null) {  

  69.                is.close();  

  70.            }  

  71. if (os != null) {  

  72.                os.close();  

  73.            }  

  74.        }  

  75. return result;  

  76.    }  

  77. /**

  78.     * upload

  79.     *

  80.     * @throws java.lang.Exception

  81.     * @return

  82.     * @param filename

  83.     */

  84. publiclong upload(String filename) throws Exception {  

  85.        String newname = "";  

  86. if (filename.indexOf("/") > -1) {  

  87.            newname = filename.substring(filename.lastIndexOf("/") + 1);  

  88.        } else {  

  89.            newname = filename;  

  90.        }  

  91. return upload(filename, newname);  

  92.    }  

  93. /**

  94.     * download 從ftp下載文件到本地

  95.     *

  96.     * @throws java.lang.Exception

  97.     * @return

  98.     * @param newfilename

  99.     *            本地生成的文件名

  100.     * @param filename

  101.     *            服務器上的文件名

  102.     */

  103. publiclong download(String filename, String newfilename) throws Exception {  

  104. long result = 0;  

  105.        TelnetInputStream is = null;  

  106.        FileOutputStream os = null;  

  107. try {  

  108.            is = ftpClient.get(filename);  

  109.            java.io.File outfile = new java.io.File(newfilename);  

  110.            os = new FileOutputStream(outfile);  

  111. byte[] bytes = newbyte[1024];  

  112. int c;  

  113. while ((c = is.read(bytes)) != -1) {  

  114.                os.write(bytes, 0, c);  

  115.                result = result + c;  

  116.            }  

  117.        } catch (IOException e) {  

  118.            e.printStackTrace();  

  119.        } finally {  

  120. if (is != null) {  

  121.                is.close();  

  122.            }  

  123. if (os != null) {  

  124.                os.close();  

  125.            }  

  126.        }  

  127. return result;  

  128.    }  

  129. /**

  130.     * 取得某個目錄下的所有文件列表

  131.     *

  132.     */

  133. public List getFileList(String path) {  

  134.        List list = new ArrayList();  

  135. try {  

  136.            DataInputStream dis = new DataInputStream(ftpClient.nameList(path));  

  137.            String filename = "";  

  138. while ((filename = dis.readLine()) != null) {  

  139.                list.add(filename);  

  140.            }  

  141.        } catch (Exception e) {  

  142.            e.printStackTrace();  

  143.        }  

  144. return list;  

  145.    }  

  146. /**

  147.     * closeServer 斷開與ftp服務器的鏈接

  148.     *

  149.     * @throws java.io.IOException

  150.     */

  151. publicvoid closeServer() throws IOException {  

  152. if (ftpClient != null) {  

  153.                ftpClient.closeServer();  

  154.            }  

  155.    }  

  156. }  



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章