UploaderServlet.java
001 | package gson.demo; |
002 |
003 | /** |
004 | * @author ____′↘夏悸 |
005 | * <a href="http://bbs.btboys.com/">Easyui 中文社区</a> |
006 | * <a href="http://easyui.btboys.com/">Easyui 学习班</a> |
007 | */ |
008 | import java.io.BufferedOutputStream; |
009 | import java.io.File; |
010 | import java.io.FileOutputStream; |
011 | import java.io.IOException; |
012 | import java.util.List; |
013 | import java.util.UUID; |
014 |
015 | import javax.servlet.ServletConfig; |
016 | import javax.servlet.ServletException; |
017 | import javax.servlet.http.HttpServlet; |
018 | import javax.servlet.http.HttpServletRequest; |
019 | import javax.servlet.http.HttpServletResponse; |
020 |
021 | import org.apache.commons.fileupload.FileItem; |
022 | import org.apache.commons.fileupload.FileUploadException; |
023 | import org.apache.commons.fileupload.disk.DiskFileItemFactory; |
024 | import org.apache.commons.fileupload.servlet.ServletFileUpload; |
025 | import org.apache.commons.io.FileUtils; |
026 | import org.apache.commons.io.FilenameUtils; |
027 |
028 | public class UploaderServlet extends HttpServlet { |
029 |
030 | private static final long serialVersionUID = 1L; |
031 | String repositoryPath; |
032 | String uploadPath; |
033 |
034 | @SuppressWarnings ( "unchecked" ) |
035 | public void doPost(HttpServletRequest request, HttpServletResponse response) |
036 | throws ServletException, IOException { |
037 | response.setCharacterEncoding( "UTF-8" ); |
038 | Integer schunk = null ; //分割块数 |
039 | Integer schunks = null ; //总分割数 |
040 | String name = null ; //文件名 |
041 | BufferedOutputStream outputStream= null ; |
042 | if (ServletFileUpload.isMultipartContent(request)) { |
043 | try { |
044 | DiskFileItemFactory factory = new DiskFileItemFactory(); |
045 | factory.setSizeThreshold( 1024 ); |
046 | factory.setRepository( new File(repositoryPath)); //设置临时目录 |
047 | ServletFileUpload upload = new ServletFileUpload(factory); |
048 | upload.setHeaderEncoding( "UTF-8" ); |
049 | upload.setSizeMax( 5 * 1024 * 1024 ); //设置附近大小 |
050 | List<FileItem> items = upload.parseRequest(request); |
051 | //生成新文件名 |
052 | String newFileName = null ; |
053 | for (FileItem item : items) { |
054 | if (!item.isFormField()) { // 如果是文件类型 |
055 | name = item.getName(); // 获得文件名 |
056 | newFileName = UUID.randomUUID().toString().replace( "-" , "" ).concat( "." ).concat(FilenameUtils.getExtension(name)); |
057 | if (name != null ) { |
058 | String nFname = newFileName; |
059 | if (schunk != null ) { |
060 | nFname = schunk + "_" + name; |
061 | } |
062 | File savedFile = new File(uploadPath, nFname); |
063 | item.write(savedFile); |
064 | } |
065 | } else { |
066 | //判断是否带分割信息 |
067 | if (item.getFieldName().equals( "chunk" )) { |
068 | schunk = Integer.parseInt(item.getString()); |
069 | } |
070 | if (item.getFieldName().equals( "chunks" )) { |
071 | schunks = Integer.parseInt(item.getString()); |
072 | } |
073 | } |
074 | } |
075 | |
076 | if (schunk != null && schunk + 1 == schunks) { |
077 | outputStream = new BufferedOutputStream( new FileOutputStream( new File(uploadPath, newFileName))); |
078 | //遍历文件合并 |
079 | for ( int i = 0 ; i < schunks; i++) { |
080 | File tempFile= new File(uploadPath,i+ "_" +name); |
081 | byte [] bytes=FileUtils.readFileToByteArray(tempFile); |
082 | outputStream.write(bytes); |
083 | outputStream.flush(); |
084 | tempFile.delete(); |
085 | } |
086 | outputStream.flush(); |
087 | } |
088 | response.getWriter().write( "{\"status\":true,\"newName\":\"" +newFileName+ "\"}" ); |
089 | } catch (FileUploadException e) { |
090 | e.printStackTrace(); |
091 | response.getWriter().write( "{\"status\":false}" ); |
092 | } catch (Exception e) { |
093 | e.printStackTrace(); |
094 | response.getWriter().write( "{\"status\":false}" ); |
095 | } finally { |
096 | try { |
097 | if (outputStream!= null ) |
098 | outputStream.close(); |
099 | } catch (IOException e) { |
100 | e.printStackTrace(); |
101 | } |
102 | } |
103 | } |
104 | } |
105 |
106 | @Override |
107 | public void init(ServletConfig config) throws ServletException { |
108 | repositoryPath = FileUtils.getTempDirectoryPath(); |
109 | uploadPath = config.getServletContext().getRealPath(config.getInitParameter( "uploadPath" )); |
110 | File up = new File(uploadPath); |
111 | if (!up.exists()){ |
112 | up.mkdir(); |
113 | } |
114 | } |
115 | } |
web.xml
01 | < servlet > |
02 | < servlet-name >Uploader</ servlet-name > |
03 | < servlet-class >gson.demo.UploaderServlet</ servlet-class > |
04 | < init-param > |
05 | < param-name >uploadPath</ param-name > |
06 | < param-value >/WEB-INF/upload</ param-value > |
07 | </ init-param > |
08 | </ servlet > |
09 |
10 | < servlet-mapping > |
11 | < servlet-name >Uploader</ servlet-name > |
12 | < url-pattern >/uploader</ url-pattern > |
13 | </ servlet-mapping > |
index.jsp
01 | <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> |
02 | <% |
03 | String path = request.getContextPath(); |
04 | String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/"; |
05 | %> |
06 |
07 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> |
08 | < html > |
09 | < head > |
10 | < base href="<%=basePath%>"> |
11 | < title >GodSon Easyui 结合Pluplaod插件的上传演示</ title > |
12 | < link rel = "stylesheet" href = "bootstrap/easyui.css" type = "text/css" ></ link > |
13 | < script type = "text/javascript" src = "jquery-1.8.0.min.js" ></ script > |
14 | < script type = "text/javascript" src = "easyui/jquery.easyui.min.js" ></ script > |
15 | < script type = "text/javascript" > |
16 | /** |
17 | * 创建上传窗口 公共方法 |
18 | * @param chunk 是否分割大文件 |
19 | * @param callBack 上传成功之后的回调 |
20 | */ |
21 | function Uploader(chunk,callBack){ |
22 | var addWin = $('< div style = "overflow: hidden;" />'); |
23 | var upladoer = $('< iframe />'); |
24 | upladoer.attr({'src':'<%=basePath%>/uploader.jsp?chunk='+chunk,width:'100%',height:'100%',frameborder:'0',scrolling:'no'}); |
25 | addWin.window({ |
26 | title:"上传文件", |
27 | height:350, |
28 | width:550, |
29 | minimizable:false, |
30 | modal:true, |
31 | collapsible:false, |
32 | maximizable:false, |
33 | resizable:false, |
34 | content:upladoer, |
35 | onClose:function(){ |
36 | var fw = GetFrameWindow(upladoer[0]); |
37 | var files = fw.files; |
38 | $(this).window('destroy'); |
39 | callBack.call(this,files); |
40 | }, |
41 | onOpen:function(){ |
42 | var target = $(this); |
43 | setTimeout(function(){ |
44 | var fw = GetFrameWindow(upladoer[0]); |
45 | fw.target = target; |
46 | },100); |
47 | } |
48 | }); |
49 | } |
50 |
51 | /** |
52 | * 根据iframe对象获取iframe的window对象 |
53 | * @param frame |
54 | * @returns {Boolean} |
55 | */ |
56 | function GetFrameWindow(frame){ |
57 | return frame && typeof(frame)=='object' && frame.tagName == 'IFRAME' && frame.contentWindow; |
58 | } |
59 | |
60 | function makerUpload(chunk){ |
61 | Uploader(chunk,function(files){ |
62 | if(files && files.length>0){ |
63 | $("#res").text("成功上传:"+files.join(",")); |
64 | } |
65 | }); |
66 | } |
67 | </ script > |
68 | </ head > |
69 | < body style = "width: 100%;height: 100%;overflow:hidden;margin: 0;padding: 0;" > |
70 | < h1 >GodSon Easyui 结合Pluplaod插件的上传演示</ h1 > |
71 | < hr /> |
72 | < a class = "easyui-linkbutton" href = "javascript:makerUpload(false)" >不分割文件上传</ a > < a class = "easyui-linkbutton" href = "javascript:makerUpload(true)" >分割文件上传</ a > |
73 | < hr /> |
74 | < div id = "res" ></ div > |
75 | </ body > |
76 | </ html > |
upload.jsp
01 | <%@ page language= "java" import= "java.util.*" pageEncoding= "UTF-8" %> |
02 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" > |
03 | <html> |
04 | <head> |
05 | <title>文件上传</title> |
06 | <link rel= "stylesheet" href= "plupload/queue/css/jquery.plupload.queue.css" type= "text/css" ></link> |
07 | <script type= "text/javascript" src= "jquery-1.8.0.min.js" ></script> |
08 | <script type= "text/javascript" src= "plupload/plupload.js" ></script> |
09 | <script type= "text/javascript" src= "plupload/plupload.html4.js" ></script> |
10 | <script type= "text/javascript" src= "plupload/plupload.html5.js" ></script> |
11 | <script type= "text/javascript" src= "plupload/plupload.flash.js" ></script> |
12 | <script type= "text/javascript" src= "plupload/zh_CN.js" ></script> |
13 | <script type= "text/javascript" src= "plupload/queue/jquery.plupload.queue.js" ></script> |
14 | <body style= "padding: 0;margin: 0;" > |
15 | <div id= "uploader" > </div> |
16 | <script type= "text/javascript" > |
17 | var files = []; |
18 | var errors = []; |
19 | var type = 'file' ; |
20 | var chunk = eval( '${param.chunk}' ); |
21 | var max_file_size = '5mb' ; |
22 | var filters = {title : "文档" , extensions : "zip,doc,docx,xls,xlsx,ppt,pptx" }; |
23 | $( "#uploader" ).pluploadQueue($.extend({ |
24 | runtimes : 'flash,html4,html5' , |
25 | url : 'uploader' , |
26 | max_file_size : max_file_size, |
27 | file_data_name: 'file' , |
28 | unique_names: true , |
29 | filters : [filters], |
30 | flash_swf_url : 'plupload/plupload.flash.swf' , |
31 | init:{ |
32 | FileUploaded: function (uploader,file,response){ |
33 | if (response.response){ |
34 | var rs = $.parseJSON(response.response); |
35 | if (rs.status){ |
36 | files.push(file.name); |
37 | } else { |
38 | errors.push(file.name); |
39 | } |
40 | } |
41 | }, |
42 | UploadComplete: function (uploader,fs){ |
43 | var e= errors.length ? ",失败" +errors.length+ "个(" +errors.join( "、" )+ ")。" : "。" ; |
44 | alert( "上传完成!共" +fs.length+ "个。成功" +files.length+e); |
45 | target.window( "close" ); |
46 | } |
47 | } |
48 | },(chunk ? {chunk_size: '1mb' } : {}))); |
49 | </script> |
50 | </body> |
51 | </html> |