首先封装一个Map,当Map可以一键多值
public class ArrayMap { private HashMap<String, List<String>> map = null ; private static final long serialVersionUID = 7760971972716111286L; public ArrayMap(){ map = new HashMap<String, List<String>>(); } public List<String> put(String key, List<String> arg1) { return map.put(key, arg1); } public List<String> put(String key, String value) { List<String>values=map.get(key); if(values == null){ values = new Vector<String>(); } values.add( value ); return map.put(key, values ) ; } public String getItem(String key){ List<String>values=map.get(key); if(Helper.isEmpty(values)){ return null; } return values.get(0) ; } public List<String> getItems(String key){ return map.get(key) ; } }
然后每次请求后调用次方法。
public ArrayMap upload(HttpServletRequest request){ ArrayMap map = new ArrayMap(); ServletRequestContext requestContext = new ServletRequestContext(request); boolean isMultipart = ServletFileUpload.isMultipartContent( requestContext ) ; if(isMultipart){ try{ String basePath = "../goodImg/" + DateFormatUtils.format(Calendar.getInstance() , "yyyyMM") + "/" ; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<?> fileItems = upload.parseRequest(request); for(Object item : fileItems){ FileItem fileItem = (FileItem) item ; if(fileItem.isFormField()){ map.put( fileItem.getFieldName() , new String(TransformUtils.toString(fileItem.getString()).getBytes("ISO-8859-1") , "GBK") ); }else{ String filePath = request.getSession().getServletContext().getRealPath("/") ; String uploadName = TransformUtils.toString(fileItem.getName()); if(!Helper.isEmpty(uploadName)){ int index = uploadName.lastIndexOf(".") ; String ext = ".jpg" ; if(index != -1){ ext = uploadName.substring( index ) ; } String fileName = basePath+TransformUtils.toString(System.currentTimeMillis()) + ext ; java.io.File file = new java.io.File(filePath + fileName); file.getParentFile().mkdirs() ; FileUtil.write( fileItem.getInputStream() , new FileOutputStream( file )) ; map.put( fileItem.getFieldName() , fileName ); } } } }catch(Exception e){ e.printStackTrace() ; } }else{ Enumeration<?> enumeration = request.getParameterNames(); while(enumeration.hasMoreElements()){ String name = TransformUtils.toString(enumeration.nextElement()); String[]values = request.getParameterValues( name ) ; if(null != values){ for(String value : values ){ map.put(name , value ) ; } } } } return map; }
原文地址:http://blog.csdn.net/hfmbook/article/details/41348859