一、需求和背景:公司内网月度会议文档过大有的超过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:
- <%@ 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="css/default.css" mce_href="css/default.css" rel="stylesheet" type="text/css" />
- <mce:script type="text/javascript" src="js/swfupload/swfupload.js" mce_src="js/swfupload/swfupload.js"></mce:script>
- <mce:script type="text/javascript" src="js/swfupload/swfupload.queue.js" mce_src="js/swfupload/swfupload.queue.js"></mce:script>
- <mce:script type="text/javascript" src="js/swfupload/fileprogress.js" mce_src="js/swfupload/fileprogress.js"></mce:script>
- <mce:script type="text/javascript" src="js/swfupload/handlers.js" mce_src="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>
<%@ 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配置:
- <?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>
<?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上传):
- 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;
- }
-
- }
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
效果图:
另外在网上google了下Cos ,FileUpload ,SmartUpload 上传文件性能比较,自己也测试了下Cos和struts upload,发现的确Cos是挺快的,尤其是大的附件的时候。
这个是网上其它人测试的 使用2M、20M、45M、200M的上传大小测试三种组件所花费的时间(单位为ms):