1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package fr.paris.lutece.portal.web.upload;
35
36 import fr.paris.lutece.portal.service.spring.SpringContextService;
37 import fr.paris.lutece.portal.service.util.AppLogService;
38
39 import net.sf.json.JSONArray;
40 import net.sf.json.JSONObject;
41
42 import org.apache.commons.fileupload.FileItem;
43
44 import java.io.IOException;
45
46 import java.util.ArrayList;
47 import java.util.List;
48 import java.util.Map.Entry;
49
50 import javax.servlet.ServletException;
51 import javax.servlet.http.HttpServlet;
52 import javax.servlet.http.HttpServletRequest;
53 import javax.servlet.http.HttpServletResponse;
54
55
56
57
58
59 public class UploadServlet extends HttpServlet
60 {
61 private static final long serialVersionUID = 1L;
62 private static final String JSON_FILE_SIZE = "fileSize";
63 private static final String JSON_FILE_NAME = "fileName";
64 private static final String JSON_FILES = "files";
65 private static final String JSON_UTF8_CONTENT_TYPE = "application/json; charset=UTF-8";
66
67
68
69
70 @Override
71 protected void doPost( HttpServletRequest req, HttpServletResponse response )
72 throws ServletException, IOException
73 {
74 MultipartHttpServletRequest request = (MultipartHttpServletRequest) req;
75
76 List<FileItem> listFileItems = new ArrayList<FileItem>( );
77 JSONObject json = new JSONObject( );
78 json.element( JSON_FILES, new JSONArray( ) );
79
80 for ( Entry<String, List<FileItem>> entry : ( request.getFileListMap( ) ).entrySet( ) )
81 {
82 for ( FileItem fileItem : entry.getValue( ) )
83 {
84 JSONObject jsonFile = new JSONObject( );
85 jsonFile.element( JSON_FILE_NAME, fileItem.getName( ) );
86 jsonFile.element( JSON_FILE_SIZE, fileItem.getSize( ) );
87
88
89 json.accumulate( JSON_FILES, jsonFile );
90
91 listFileItems.add( fileItem );
92 }
93 }
94
95 IAsynchronousUploadHandler handler = getHandler( request );
96
97 if ( handler == null )
98 {
99 AppLogService.error( "No handler found, removing temporary files" );
100
101 for ( FileItem fileItem : listFileItems )
102 {
103 fileItem.delete( );
104 }
105 }
106 else
107 {
108 handler.process( request, response, json, listFileItems );
109 }
110
111 if ( AppLogService.isDebugEnabled( ) )
112 {
113 AppLogService.debug( "Aysnchronous upload : " + json.toString( ) );
114 }
115
116 response.setContentType(JSON_UTF8_CONTENT_TYPE);
117 response.getWriter().print( json.toString( ) );
118 }
119
120
121
122
123
124
125
126 private IAsynchronousUploadHandler getHandler( HttpServletRequest request )
127 {
128 for ( IAsynchronousUploadHandler handler : SpringContextService.getBeansOfType(
129 IAsynchronousUploadHandler.class ) )
130 {
131 if ( handler.isInvoked( request ) )
132 {
133 return handler;
134 }
135 }
136
137 return null;
138 }
139 }