1 19 20 package za.org.coefficient.util.common; 21 22 import java.util.Arrays ; 23 import java.util.Collections ; 24 import java.util.Enumeration ; 25 import java.util.HashMap ; 26 import java.util.Iterator ; 27 import java.util.Map ; 28 29 import javax.servlet.http.HttpServletRequest ; 30 31 import org.apache.commons.fileupload.DiskFileUpload; 32 import org.apache.commons.fileupload.FileItem; 33 import org.apache.commons.fileupload.FileUploadException; 34 35 36 40 public class MultipartRequest extends BaseMultipartRequest { 41 43 public static final int DEFAULT_SIZE_MAX = 4 * 1024 * 1024; 44 45 47 private final Map parameters = new HashMap (); 48 49 51 56 public MultipartRequest(HttpServletRequest request) 57 throws FileUploadException { 58 this(request, DEFAULT_SIZE_MAX); 59 } 60 61 67 public MultipartRequest(HttpServletRequest request, int sizeMax) 68 throws FileUploadException { 69 70 DiskFileUpload upload = new DiskFileUpload(); 71 72 upload.setSizeMax(sizeMax); 74 75 for (Iterator i = upload.parseRequest(request).iterator(); i.hasNext();) { 77 FileItem item = (FileItem) i.next(); 78 if (item.isFormField()) { 79 addParameter(item.getFieldName(), item.getString()); 80 } else { 81 parameters.put(item.getFieldName(), 82 new UploadedFile(item.getContentType(), item.get(), 83 item.getName())); 84 } 85 } 86 } 87 88 94 protected void addParameter (String name, String value) { 95 String [] existing = (String [])parameters.get(name); 96 if (existing == null) { 97 parameters.put (name,new String []{value}); 98 } else { 99 String [] newValue = new String [existing.length+1]; 100 for (int i=0; i<existing.length; i++) { 101 newValue[i] = existing[i]; 102 } 103 newValue[existing.length] = value; 104 parameters.put(name, newValue); 105 } 106 } 107 108 110 115 public UploadedFile getFileParameter(String name) 116 throws FileUploadException { 117 Object o = parameters.get(name); 118 119 return (o instanceof UploadedFile) ? (UploadedFile) o : null; 120 } 121 122 public String getParameter(String name) { 123 Object o = parameters.get(name); 124 125 return (o instanceof String []) ? ((String []) o)[0] : null; 126 } 127 128 public Map getParameterMap() { 129 return Collections.unmodifiableMap(parameters); 130 } 131 132 public Enumeration getParameterNames() { 133 return Collections.enumeration(parameters.keySet()); 134 } 135 136 public String [] getParameterValues(String name) { 137 Object o = parameters.get(name); 138 139 return (o instanceof String []) ? (String []) o : null; 140 } 141 } 142 | Popular Tags |