基于jquery ajax 无刷新 文件批量上传插件 GooUploader整合struts2实现上传

今天下午安排了一个任务:要实现多文件上传,也就是批量上传文件。相信单个文件上传很多人都实现过,批量上传也有不少人实现过,我之前批量上传的做法是利用js或jquery来动态添加删除<input type="file" name="file" />的。感觉在用户体验上也不是很好,于是在网上google一把,发现大家常用的是swfupload.swf这个插件,网上也有类似的例子,但也发现了GooUploader这个插件,它是基于swfupload.swf,也就是底层封装了改插件,同时可以实现无刷新。于是在网上google一把,下了下来。下下来的可以直接放在tomcat运行了,不过它后台是基于servlet实现的。代码如下:

通过反编译工具查看的,它的底层是基于apache的两个有名的常用的组件:commons-fileupload-1.2.1和commons-io-1.4.jar实现的。

 

Java代码   收藏代码
  1. package servlet;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.PrintStream;  
  9. import java.io.PrintWriter;  
  10. import javax.servlet.Servlet;  
  11. import javax.servlet.ServletException;  
  12. import javax.servlet.http.HttpServlet;  
  13. import javax.servlet.http.HttpServletRequest;  
  14. import javax.servlet.http.HttpServletResponse;  
  15. import org.apache.commons.fileupload.FileItemIterator;  
  16. import org.apache.commons.fileupload.FileItemStream;  
  17. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  18. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  19. import org.apache.commons.fileupload.util.Streams;  
  20.   
  21. public class UploadFileServlet extends HttpServlet  
  22.   implements Servlet  
  23. {  
  24.   File tmpDir = null;  
  25.   File saveDir = null;  
  26.   
  27.   protected void doGet(HttpServletRequest request, HttpServletResponse response)  
  28.     throws ServletException, IOException  
  29.   {  
  30.     doPost(request, response);  
  31.   }  
  32.   
  33.   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  34.     try {  
  35.       request.setCharacterEncoding("UTF-8");  
  36.       if (ServletFileUpload.isMultipartContent(request)) {  
  37.         DiskFileItemFactory dff = new DiskFileItemFactory();  
  38.         dff.setRepository(this.tmpDir);  
  39.         dff.setSizeThreshold(1024000);  
  40.         ServletFileUpload sfu = new ServletFileUpload(dff);  
  41.         sfu.setFileSizeMax(109999999L);  
  42.         sfu.setSizeMax(999999999L);  
  43.         FileItemIterator fii = sfu.getItemIterator(request);  
  44.         while (fii.hasNext()) {  
  45.           FileItemStream fis = fii.next();  
  46.           if ((!fis.isFormField()) && (fis.getName().length() > 0)) {  
  47.             System.out.println(fis.getName());  
  48.             String fileName = fis.getName();  
  49.             BufferedInputStream in = new BufferedInputStream(fis.openStream());  
  50.             BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File("f:\\nokia\\" + fileName)));  
  51.             Streams.copy(in, out, true);  
  52.           }  
  53.         }  
  54.         response.getWriter().println("File upload successfully!!!");  
  55.       }  
  56.     } catch (Exception e) {  
  57.       e.printStackTrace();  
  58.     }  
  59.   }  
  60.   
  61.   public void init()  
  62.     throws ServletException  
  63.   {  
  64.     super.init();  
  65.     String tmpPath = "f:\\nokia\\";  
  66.     String savePath = "f:\\nokia\\";  
  67.     this.tmpDir = new File(tmpPath);  
  68.     this.saveDir = new File(savePath);  
  69.     if (!this.tmpDir.isDirectory())  
  70.       this.tmpDir.mkdir();  
  71.     if (!this.saveDir.isDirectory())  
  72.       this.saveDir.mkdir();  
  73.     System.out.print("UploadFileServlet init");  
  74.   }  
  75. }  

 主要就是这个servlet就实现了。由于我的项目是用ssh2,于是就考虑用struts2来实现,废话少说了,

先看效果图:

主要代码如下:

 

index.jsp

Java代码   收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9. <head>  
  10. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  11.  <title>文件上传控件GooUploader</title>  
  12. <link rel="stylesheet" type="text/css" href="codebase/GooUploader.css"/>  
  13. <script  type="text/javascript" src="codebase/jquery-1.3.2.min.js"></script>  
  14. <script  type="text/javascript" src="codebase/GooUploader.js"></script>  
  15. <script type="text/javascript" src="codebase/swfupload/swfupload.js"></script>  
  16. <script type="text/javascript">  
  17. var demo;  
  18. var  post_params = {session_id:"f1423rwe543t4wrtwerwe"};  
  19. var property={  
  20.     width:300,  
  21.     height:200,  
  22.     multiple:true,  
  23.     //file_post_name : "Filedata",  
  24.     //file_types:"*.jpg;*.gif",  
  25.   //  file_types_description: "Web Image Files",  
  26.    // post_params:post_params,  
  27.     btn_add_text:"添加",  
  28.     btn_up_text:"上传",  
  29.     btn_cancel_text:"放弃",  
  30.     btn_clean_text:"清空",  
  31.     op_del_text:"单项删除",  
  32.     op_up_text:"单项上传",  
  33.     op_fail_text:"上传失败",  
  34.     op_ok_text:"上传成功",  
  35.     op_no_text:"取消上传",  
  36.     upload_url:"uploadImage.action",  
  37.     flash_url :"codebase/swfupload.swf"  
  38. };  
  39. $(document).ready(function(){  
  40.   demo=$.createGooUploader($("#demo"),property)  
  41. });  
  42. </script>  
  43. </head>  
  44.   
  45. <body>  
  46. <br/>  
  47.   
  48. <br/>  
  49. <div id="demo"></div>  
  50. </body>  
  51. </html>  

  注意: * file_post_name : "Filedata"该参数设置了POST信息中上传文件的name值(类似传统Form中设置了<input type="file" name="uploadImg"/>的name属性)。
 * 注意:在Linux下面此参数设置无效,接收的name总为Filedata,因此为了保证最大的兼容性,建议此参数使用默认值。查到这个信息我花了3个小时搜索,最后在文档中找到了,这是用struts2实现的关键。

 

UploadAction.java

Java代码   收藏代码
  1. package com.test;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileOutputStream;  
  8. import java.io.InputStream;  
  9. import java.io.OutputStream;  
  10. import java.util.List;  
  11.   
  12. import javax.servlet.ServletContext;  
  13. import javax.servlet.http.HttpServletRequest;  
  14.   
  15. import org.apache.commons.io.FileUtils;  
  16. import org.apache.struts2.ServletActionContext;  
  17.   
  18. import com.opensymphony.xwork2.ActionSupport;  
  19.   
  20. /** 
  21.  * @author fish 
  22.  */  
  23. public class UploadAction extends ActionSupport  
  24. {  
  25.     private List<File> Filedata; // 默认的客户端文件对象,命名不符合java规范fileData  
  26.     private List<String> FiledataFileName; // 客户端文件名  
  27.     private List<String> imageContentType; // 客户端文件名类型  
  28.   
  29.     public List<File> getFiledata()  
  30.     {  
  31.         return Filedata;  
  32.     }  
  33.   
  34.     public void setFiledata(List<File> filedata)  
  35.     {  
  36.         Filedata = filedata;  
  37.     }  
  38.   
  39.     public List<String> getFiledataFileName()  
  40.     {  
  41.         return FiledataFileName;  
  42.     }  
  43.   
  44.     public void setFiledataFileName(List<String> filedataFileName)  
  45.     {  
  46.         FiledataFileName = filedataFileName;  
  47.     }  
  48.   
  49.     public List<String> getImageContentType()  
  50.     {  
  51.         return imageContentType;  
  52.     }  
  53.   
  54.     public void setImageContentType(List<String> imageContentType)  
  55.     {  
  56.         this.imageContentType = imageContentType;  
  57.     }  
  58.   
  59.     @Override  
  60.     public String execute() throws Exception  
  61.     {  
  62.         if (Filedata == null || Filedata.size() == 0)  
  63.         {  
  64.             return null;  
  65.         }  
  66.         for (int i = 0; i < Filedata.size(); ++i)  
  67.         {  
  68.   
  69.             String fileName = FiledataFileName.get(i); // 文件真名  
  70.   
  71.             long length = Filedata.get(i).length(); // 文件的真实大小  
  72.             long time = System.currentTimeMillis();  
  73.   
  74.             // 将上传的文件保存到服务器的硬盘上  
  75.   
  76.             InputStream is = new  BufferedInputStream(new FileInputStream(Filedata.get(i)));  
  77.   
  78.             HttpServletRequest request = ServletActionContext.getRequest(); // 获得ServletRequest对象  
  79.             //request.getRealPath("/")已不建议使用,改为this.getServletContext().getRealPath("/")  
  80.             System.out.println("path:"+ServletActionContext.getServletContext().getRealPath("/"));  
  81.             File tempFile = new File(ServletActionContext.getServletContext().getRealPath("/uploadimages")+File.separator+fileName);  
  82.   
  83.             FileUtils.forceMkdir(tempFile.getParentFile()); // 创建上传文件所在的父目录  
  84.   
  85.             OutputStream os = new BufferedOutputStream( new FileOutputStream(tempFile));  
  86.   
  87.             int len = 0;  
  88.             byte[] buffer = new byte[500];  
  89.   
  90.             while (-1 != (len = is.read(buffer)))  
  91.             {  
  92.                 os.write(buffer, 0, len);  
  93.                   
  94.             }  
  95.             is.close();  
  96.             os.flush();  
  97.             os.close();  
  98.         }  
  99.         return null;  
  100.     }  
  101. }  
 

struts.xml

Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5.   
  6. <struts>  
  7.   
  8.     <constant name="struts.multipart.maxSize" value="100000000000"></constant>  
  9.     <package name="upload"  extends="struts-default">  
  10.         <action name="uploadImage" class="com.test.UploadAction"></action>  
  11.     </package>  
  12.   
  13. </struts>  
 

这样就搞定了,说难也不难,说易也不易,关键是要找到类似传统Form中设置了<input type="file" name="uploadImg"/>的name属性,就可以了。若想用servlet实现,直接用源码的例子就可以了。

 

动态传参:

Java代码   收藏代码
  1. post_params={value:value};  
  2. demo.$swfUpload.setPostParams(post_params);  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值