SWFUpload+COS 上传组件+servelet 实现大附件上传

一、需求和背景:公司内网月度会议文档过大有的超过50M,原先的上传组件利用struts upload+io流如果上传文件过大会导致内存溢出。而且客户那边还迫切的希望有个大附件上传的功能。

二、

     1、[swfupload] 组件下载 http://swfupload.googlecode.com (SWFUpload v2.2.0.1 Core.zip

     2、[COS 上传组件]下载 http://www.servlets.com/cos/index.html (cos-26Dec2008.zip)

    3、将swfupload和cos整合,

     第一步:先让swfupload跑起来,编写index.jsp:

  1. <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml" >  
  4. <head>  
  5. <title>大附件上传 - Simple Demo</title>  
  6. <link href="css/default.css" mce_href="css/default.css" rel="stylesheet" type="text/css" />  
  7. <mce:script type="text/javascript" src="js/swfupload/swfupload.js" mce_src="js/swfupload/swfupload.js"></mce:script>  
  8. <mce:script type="text/javascript" src="js/swfupload/swfupload.queue.js" mce_src="js/swfupload/swfupload.queue.js"></mce:script>  
  9. <mce:script type="text/javascript" src="js/swfupload/fileprogress.js" mce_src="js/swfupload/fileprogress.js"></mce:script>  
  10. <mce:script type="text/javascript" src="js/swfupload/handlers.js" mce_src="js/swfupload/handlers.js"></mce:script>  
  11. <mce:script type="text/javascript"><!--  
  12.         var swfu;  
  13.   
  14.         window.onload = function() {  
  15.             var settings = {  
  16.                 flash_url : "swfupload/swfupload.swf",  
  17.                 upload_url: "up/upload.jsp",  
  18.                 post_params: {"uploadTimer" : new Date()},  
  19.                 file_size_limit : "200 MB",  
  20.                 file_types : "*.*",  
  21.                 file_types_description : "All Files",  
  22.                 file_upload_limit : 100,  
  23.                 file_queue_limit : 0,  
  24.                 custom_settings : {  
  25.                     progressTarget : "fsUploadProgress",  
  26.                     cancelButtonId : "btnCancel",  
  27.                     upload_successful : false  
  28.                 },  
  29.                 debug: false,  
  30.   
  31.                 // Button settings  
  32.                 button_image_url : "images/XPButtonUploadText_61x22.png",  
  33.                 button_placeholder_id : "spanButtonPlaceholder",  
  34.                 button_width: 61,  
  35.                 button_height: 22,  
  36.                   
  37.                 // The event handler functions are defined in handlers.js  
  38.                 file_queued_handler : fileQueued,  
  39.                 file_queue_error_handler : fileQueueError,  
  40.                 file_dialog_complete_handler : fileDialogComplete,  
  41.                 upload_start_handler : uploadStart,  
  42.                 upload_progress_handler : uploadProgress,  
  43.                 upload_error_handler : uploadError,  
  44.                 upload_success_handler : uploadSuccess,  
  45.                 upload_complete_handler : uploadComplete,  
  46.                 queue_complete_handler : queueComplete  // Queue plugin event  
  47.             };  
  48.   
  49.             swfu = new SWFUpload(settings);  
  50.          };  
  51.       
  52. // --></mce:script>  
  53. </head>  
  54. <body>  
  55.   
  56. <div id="content">  
  57.     <h2></h2>  
  58.     <form id="form1" action="index.jsp" method="post" enctype="multipart/form-data">  
  59.         <p>This page demonstrates a simple usage of SWFUpload.  It uses the Queue Plugin to simplify uploading or cancelling all queued files.</p>  
  60.   
  61.             <div class="fieldset flash" id="fsUploadProgress">  
  62.             <span class="legend">Upload Queue</span>  
  63.             </div>  
  64.         <div id="divStatus">0 Files Uploaded</div>  
  65.             <div>  
  66.                 <span id="spanButtonPlaceHolder"></span>  
  67.                 <input id="btnCancel" type="button" value="Cancel All Uploads" onclick="swfu.cancelQueue();" disabled="disabled" style="margin-left: 2px; font-size: 8pt; height: 29px;" />  
  68.             </div>  
  69.   
  70.     </form>  
  71. </div>  
  72. </body>  
  73. </html>  
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>大附件上传 - Simple Demo</title> <link href="http://ljhmustang.blog.163.com/blog/css/default.css" mce_href="http://ljhmustang.blog.163.com/blog/css/default.css" rel="stylesheet" type="text/css" /> <mce:script type="text/javascript" src="http://ljhmustang.blog.163.com/blog/js/swfupload/swfupload.js" mce_src="http://ljhmustang.blog.163.com/blog/js/swfupload/swfupload.js"></mce:script> <mce:script type="text/javascript" src="http://ljhmustang.blog.163.com/blog/js/swfupload/swfupload.queue.js" mce_src="http://ljhmustang.blog.163.com/blog/js/swfupload/swfupload.queue.js"></mce:script> <mce:script type="text/javascript" src="http://ljhmustang.blog.163.com/blog/js/swfupload/fileprogress.js" mce_src="http://ljhmustang.blog.163.com/blog/js/swfupload/fileprogress.js"></mce:script> <mce:script type="text/javascript" src="http://ljhmustang.blog.163.com/blog/js/swfupload/handlers.js" mce_src="http://ljhmustang.blog.163.com/blog/js/swfupload/handlers.js"></mce:script> <mce:script type="text/javascript"><!-- var swfu; window.onload = function() { var settings = { flash_url : "swfupload/swfupload.swf", upload_url: "up/upload.jsp", post_params: {"uploadTimer" : new Date()}, file_size_limit : "200 MB", file_types : "*.*", file_types_description : "All Files", file_upload_limit : 100, file_queue_limit : 0, custom_settings : { progressTarget : "fsUploadProgress", cancelButtonId : "btnCancel", upload_successful : false }, debug: false, // Button settings button_image_url : "images/XPButtonUploadText_61x22.png", button_placeholder_id : "spanButtonPlaceholder", button_width: 61, button_height: 22, // The event handler functions are defined in handlers.js file_queued_handler : fileQueued, file_queue_error_handler : fileQueueError, file_dialog_complete_handler : fileDialogComplete, upload_start_handler : uploadStart, upload_progress_handler : uploadProgress, upload_error_handler : uploadError, upload_success_handler : uploadSuccess, upload_complete_handler : uploadComplete, queue_complete_handler : queueComplete // Queue plugin event }; swfu = new SWFUpload(settings); }; // --></mce:script> </head> <body> <div id="content"> <h2></h2> <form id="form1" action="index.jsp" method="post" enctype="multipart/form-data"> <p>This page demonstrates a simple usage of SWFUpload. It uses the Queue Plugin to simplify uploading or cancelling all queued files.</p> <div class="fieldset flash" id="fsUploadProgress"> <span class="legend">Upload Queue</span> </div> <div id="divStatus">0 Files Uploaded</div> <div> <span id="spanButtonPlaceHolder"></span> <input id="btnCancel" type="button" value="Cancel All Uploads" onclick="swfu.cancelQueue();" disabled="disabled" style="margin-left: 2px; font-size: 8pt; height: 29px;" /> </div> </form> </div> </body> </html>

注:1、所有的js和css文件都是从官网上下载下来的,没有什么特殊的改变。

      2、upload_url: "up/upload.jsp",这里的“up/upload.jsp”可以用一个jsp页面写上传类(cos),我这里用servelet配置的路径

2、web.xm配置:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  3.     <display-name>upload</display-name>  
  4.     <welcome-file-list>  
  5.         <welcome-file>index.html</welcome-file>  
  6.         <welcome-file>index.htm</welcome-file>  
  7.         <welcome-file>index.jsp</welcome-file>  
  8.         <welcome-file>default.html</welcome-file>  
  9.         <welcome-file>default.htm</welcome-file>  
  10.         <welcome-file>default.jsp</welcome-file>  
  11.     </welcome-file-list>  
  12.     <servlet>  
  13.         <servlet-name>SimpleUploader</servlet-name>  
  14.         <servlet-class>com.servlet.uploader.SimpleUploaderServlet</servlet-class>  
  15.         <init-param>  
  16.             <param-name>fileSizeLimit</param-name>  
  17.             <param-value>500</param-value>  
  18.         </init-param>  
  19.     </servlet>  
  20.     <servlet-mapping>  
  21.         <servlet-name>SimpleUploader</servlet-name>  
  22.         <url-pattern>/up/upload.jsp</url-pattern>  
  23.     </servlet-mapping>  
  24. </web-app>  
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>upload</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>SimpleUploader</servlet-name> <servlet-class>com.servlet.uploader.SimpleUploaderServlet</servlet-class> <init-param> <param-name>fileSizeLimit</param-name> <param-value>500</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>SimpleUploader</servlet-name> <url-pattern>/up/upload.jsp</url-pattern> </servlet-mapping> </web-app>

注:1、fileSizeLimit是配置允许上传大小的500,代表500M。

     

   3、编写 SimpleUploaderServlet类(利用cos.jar上传):

  1. package com.servlet.uploader;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.util.Enumeration;  
  6.   
  7. import javax.servlet.ServletConfig;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12. import javax.servlet.http.HttpSession;  
  13.   
  14. import org.apache.commons.io.FilenameUtils;  
  15. import org.apache.commons.lang.StringUtils;  
  16. import org.apache.commons.lang.time.DateFormatUtils;  
  17.   
  18. import com.oreilly.servlet.MultipartRequest;  
  19. import com.oreilly.servlet.multipart.FileRenamePolicy;  
  20.   
  21. public class SimpleUploaderServlet extends HttpServlet {  
  22.   
  23.     private static final long serialVersionUID = -3096800116651263134L;  
  24.   
  25.     private String fileSizeLimit;  
  26.   
  27.     public void init(ServletConfig config) throws ServletException {  
  28.         this.fileSizeLimit = config.getInitParameter("fileSizeLimit");  
  29.     }  
  30.   
  31.     public void destroy() {  
  32.         this.fileSizeLimit = null;  
  33.         super.destroy();  
  34.     }  
  35.   
  36.     class MyFileRenamePolicy implements FileRenamePolicy {  
  37.         public File rename(File file) {  
  38.             String fileSaveName = StringUtils.join(new String[] { java.util.UUID.randomUUID().toString(), ".",  
  39.                     FilenameUtils.getExtension(file.getName()) });  
  40.             File result = new File(file.getParentFile(), fileSaveName);  
  41.             return result;  
  42.         }  
  43.     }  
  44.   
  45.     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  46.   
  47.         System.out.println("--- BEGIN DOPOST ---");  
  48.   
  49.         HttpSession session = request.getSession();  
  50.           
  51.         String uploadDir = "files" + File.separatorChar + "upload" + File.separatorChar;  
  52.         String autoCreatedDateDirByParttern = "yyyy" + File.separatorChar + "MM" + File.separatorChar + "dd"  
  53.                 + File.separatorChar;  
  54.         String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(), autoCreatedDateDirByParttern);  
  55.         String ctxDir = session.getServletContext().getRealPath(String.valueOf(File.separatorChar));  
  56.         if (!ctxDir.endsWith(String.valueOf(File.separatorChar))) {  
  57.             ctxDir = ctxDir + File.separatorChar;  
  58.         }  
  59.         File savePath = new File(ctxDir + uploadDir + autoCreatedDateDir);  
  60.         if (!savePath.exists()) {  
  61.             savePath.mkdirs();  
  62.         }  
  63.   
  64.         String saveDirectory = ctxDir + uploadDir + autoCreatedDateDir;  
  65.           
  66.         if (StringUtils.isBlank(this.fileSizeLimit.toString())) {  
  67.             this.fileSizeLimit = "100";// 默认 100M  
  68.         }  
  69.         int maxPostSize = Integer.valueOf(this.fileSizeLimit).intValue() * 1024 * 1024;  
  70.           
  71.         String encoding = "GBK";  
  72.         FileRenamePolicy rename = new MyFileRenamePolicy();  
  73.         MultipartRequest multi = null;  
  74.         try {  
  75.             multi = new MultipartRequest(request, saveDirectory, maxPostSize, encoding, rename);  
  76.         } catch (IOException e) {  
  77.             System.out.println(e.getMessage());  
  78.             return;  
  79.         }  
  80.   
  81.         // 输出  
  82.         Enumeration files = multi.getFileNames();  
  83.         while (files.hasMoreElements()) {  
  84.             String name = (String) files.nextElement();  
  85.             File f = multi.getFile(name);  
  86.             if (f != null) {  
  87.                 String fileName = multi.getFilesystemName(name);  
  88.                 String lastFileName = saveDirectory + "\\" + fileName;  
  89.                 String fileSavePath = uploadDir + autoCreatedDateDir + fileName;  
  90.                 System.out.println("SimpleUploaderServlet");  
  91.                 System.out.println("文件地址:" + lastFileName);  
  92.                 System.out.println(" 保存路径:" + fileSavePath);  
  93.             }  
  94.         }  
  95.   
  96.         System.out.println("--- END DOPOST ---");  
  97.   
  98.     }  
  99.   
  100.     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  101.         this.doPost(request, response);  
  102.     }  
  103.   
  104.     public String getFileSizeLimit() {  
  105.         return fileSizeLimit;  
  106.     }  
  107.   
  108.     public void setFileSizeLimit(String fileSizeLimit) {  
  109.         this.fileSizeLimit = fileSizeLimit;  
  110.     }  
  111.   
  112. }  
package com.servlet.uploader; import java.io.File; import java.io.IOException; import java.util.Enumeration; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateFormatUtils; import com.oreilly.servlet.MultipartRequest; import com.oreilly.servlet.multipart.FileRenamePolicy; public class SimpleUploaderServlet extends HttpServlet { private static final long serialVersionUID = -3096800116651263134L; private String fileSizeLimit; public void init(ServletConfig config) throws ServletException { this.fileSizeLimit = config.getInitParameter("fileSizeLimit"); } public void destroy() { this.fileSizeLimit = null; super.destroy(); } class MyFileRenamePolicy implements FileRenamePolicy { public File rename(File file) { String fileSaveName = StringUtils.join(new String[] { java.util.UUID.randomUUID().toString(), ".", FilenameUtils.getExtension(file.getName()) }); File result = new File(file.getParentFile(), fileSaveName); return result; } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("--- BEGIN DOPOST ---"); HttpSession session = request.getSession(); String uploadDir = "files" + File.separatorChar + "upload" + File.separatorChar; String autoCreatedDateDirByParttern = "yyyy" + File.separatorChar + "MM" + File.separatorChar + "dd" + File.separatorChar; String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(), autoCreatedDateDirByParttern); String ctxDir = session.getServletContext().getRealPath(String.valueOf(File.separatorChar)); if (!ctxDir.endsWith(String.valueOf(File.separatorChar))) { ctxDir = ctxDir + File.separatorChar; } File savePath = new File(ctxDir + uploadDir + autoCreatedDateDir); if (!savePath.exists()) { savePath.mkdirs(); } String saveDirectory = ctxDir + uploadDir + autoCreatedDateDir; if (StringUtils.isBlank(this.fileSizeLimit.toString())) { this.fileSizeLimit = "100";// 默认100M } int maxPostSize = Integer.valueOf(this.fileSizeLimit).intValue() * 1024 * 1024; String encoding = "GBK"; FileRenamePolicy rename = new MyFileRenamePolicy(); MultipartRequest multi = null; try { multi = new MultipartRequest(request, saveDirectory, maxPostSize, encoding, rename); } catch (IOException e) { System.out.println(e.getMessage()); return; } // 输出 Enumeration files = multi.getFileNames(); while (files.hasMoreElements()) { String name = (String) files.nextElement(); File f = multi.getFile(name); if (f != null) { String fileName = multi.getFilesystemName(name); String lastFileName = saveDirectory + "\\" + fileName; String fileSavePath = uploadDir + autoCreatedDateDir + fileName; System.out.println("SimpleUploaderServlet"); System.out.println("文件地址:" + lastFileName); System.out.println("保存路径:" + fileSavePath); } } System.out.println("--- END DOPOST ---"); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public String getFileSizeLimit() { return fileSizeLimit; } public void setFileSizeLimit(String fileSizeLimit) { this.fileSizeLimit = fileSizeLimit; } }

注:1、MyFileRenamePolicy是自定义文件重命名的方法。

另外考虑到cos与struts1.x的结合有缺陷,如果想保存上传后的文件信息,可以利用别的方法,如存入到session中。

demo下载地址:http://download.csdn.net/source/2180135

效果图:

SWFUpload+COS 上传组件+servelet 实现大附件上传_第1张图片

另外在网上google了下Cos ,FileUpload ,SmartUpload 上传文件性能比较,自己也测试了下Cos和struts upload,发现的确Cos是挺快的,尤其是大的附件的时候。

这个是网上其它人测试的 使用2M20M45M200M的上传大小测试三种组件所花费的时间(单位为ms

你可能感兴趣的:(JavaScript,jsp,servlet,css,Blog)