Revize 700a51d4
Přidáno uživatelem Tomáš Šimandl před více než 6 roky(ů)
sources/src/main/java/cz/zcu/kiv/offscreen/storage/FileLoader.java | ||
---|---|---|
1 |
package cz.zcu.kiv.offscreen.storage; |
|
2 |
|
|
3 |
import org.apache.commons.fileupload.FileItem; |
|
4 |
import org.apache.commons.fileupload.disk.DiskFileItemFactory; |
|
5 |
import org.apache.commons.fileupload.servlet.ServletFileUpload; |
|
6 |
import org.apache.log4j.Logger; |
|
7 |
|
|
8 |
import javax.servlet.http.HttpServletRequest; |
|
9 |
import java.util.HashMap; |
|
10 |
import java.util.List; |
|
11 |
import java.util.Map; |
|
12 |
|
|
13 |
public class FileLoader { |
|
14 |
|
|
15 |
private static final int MAX_FILE_SIZE = 512000000; |
|
16 |
private static final String ACCEPTED_EXTENSION_FILE = "json"; |
|
17 |
|
|
18 |
private Logger logger = Logger.getLogger(FileLoader.class); |
|
19 |
|
|
20 |
/** |
|
21 |
* Get multipart data from request which was send and return it as a map where key is field name from form and |
|
22 |
* second value are data as string. |
|
23 |
* |
|
24 |
* @return loaded multipart data in map or empty map. |
|
25 |
*/ |
|
26 |
public Map<String, String> loadFile(HttpServletRequest request){ |
|
27 |
|
|
28 |
DiskFileItemFactory factory = new DiskFileItemFactory(); |
|
29 |
|
|
30 |
ServletFileUpload upload = new ServletFileUpload(factory); |
|
31 |
upload.setSizeMax(MAX_FILE_SIZE); |
|
32 |
|
|
33 |
Map<String, String> resultMap = new HashMap<>(); |
|
34 |
|
|
35 |
try { |
|
36 |
|
|
37 |
List<FileItem> fileItems = upload.parseRequest(request); |
|
38 |
for (FileItem item : fileItems) { |
|
39 |
if (item.isFormField()) { |
|
40 |
resultMap.put(item.getFieldName(), item.getString()); |
|
41 |
} else { |
|
42 |
if (isAcceptedExtension(item.getName()) && item.getSize() > 0) { |
|
43 |
logger.debug(item.getName() + " - " + item.getContentType()); |
|
44 |
resultMap.put(item.getFieldName(), item.getString("UTF-8")); |
|
45 |
} else { |
|
46 |
resultMap.put(item.getFieldName(), ""); |
|
47 |
} |
|
48 |
} |
|
49 |
} |
|
50 |
|
|
51 |
} catch (Exception ex) { |
|
52 |
ex.printStackTrace(); |
|
53 |
} |
|
54 |
return resultMap; |
|
55 |
} |
|
56 |
|
|
57 |
/** |
|
58 |
* Check if input string ends with allowed extension. |
|
59 |
* |
|
60 |
* @param componentName all name of file |
|
61 |
* @return true - if extension is allowed, false - otherwise. |
|
62 |
*/ |
|
63 |
private boolean isAcceptedExtension(String componentName) { |
|
64 |
return componentName.endsWith("." + ACCEPTED_EXTENSION_FILE); |
|
65 |
} |
|
66 |
} |
Také k dispozici: Unified diff
Added FileLoader class