struts.multipart 和 commons-fileupload上传插件解析
使用的是struts2和commons-fileupload2.1.1
昨天遇到一个上传功能的错误,很是奇怪,原因是有的时候能够上传成功,有的不能上传成功,最为奇特的是需要报个错误,才能上传成功,不报错的就不能上传成功。今天算是弄清楚了,特地做个记录,首先报错的代码如下。
org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (5727) exceeds the configured maximum (4028)
request.setCharacterEncoding("UTF-8");LoadPath loadPath = new LoadPath();String path = loadPath.getUploadPath();String fileName = "";boolean isFlg = false;Util u = new Util();// 判断有没有这个日期目录String currData = u.getSysDate("yyyyMMdd");// 判断目录在不,如果不在那么就添加一个目录path = path + "/" + currData;File dir = new File(path);if (!dir.exists()) {// 不存在,需要创建目录try {dir.mkdir();this.log("创建目录:" + dir);} catch (Exception ex) {log.error("创建目录:" + path + "失败,原因:" + ex.toString());}}// 文件上传部分boolean isMultipart = ServletFileUpload.isMultipartContent(request);if (isMultipart == true) {DiskFileItemFactory factory = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);try {List<FileItem> items = upload.parseRequest(request);// 上传文件解析Iterator<FileItem> itr = items.iterator();// 枚举方法while (itr.hasNext()) {FileItem item = (FileItem) itr.next();if (item.isFormField()) {// 判断是文件还是文本信息} else {if (item.getName() != null&& !item.getName().equals("")) {// 判断是否选择了文件long time = System.currentTimeMillis();String temPath = item.getName();// 返回上传文件在客户端的完整路径名称fileName = temPath.substring(temPath.lastIndexOf("\") + 1, temPath.length());// 原来文件名String oldName = fileName.substring(0, fileName.lastIndexOf("."));// 文件名String fileNameAtt = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());// 文件后缀名String newName = time + "." + fileNameAtt;// 此时文件暂存在服务器的内存当中log.info("保存地址:" + path);File file = new File(path, newName);// 获取根目录对应的真实物理路径item.write(file);// 保存文件在服务器的物理磁盘中// 上传文件成功!isFlg = true;String loadPathStr = "upload/"+currData+"/"+newName;AppContext.getWySysFileManagerLogic().save(oldName, time+"", loadPathStr, Integer.parseInt(item.getSize()+""));}}}} catch (Exception e) {e.printStackTrace();log.info("文件上传失败!");}} else {log.info("上传数据格式不是 multipart/form-data");}List<FileItem> items = upload.parseRequest(request);// 上传文件解析Iterator<FileItem> itr = items.iterator();// 枚举方法
struts.multipart.maxSize=4028
if (sizeMax >= 0) { int requestSize = ctx.getContentLength();if (requestSize == -1) { input = new LimitedInputStream(input, sizeMax) {protected void raiseError(long pSizeMax, long pCount)throws IOException { FileUploadException ex =new SizeLimitExceededException( "the request was rejected because" + " its size (" + pCount + ") exceeds the configured maximum" + " (" + pSizeMax + ")", pCount, pSizeMax); throw new FileUploadIOException(ex);} };} else { if (sizeMax >= 0 && requestSize > sizeMax) {throw new SizeLimitExceededException("the request was rejected because its size ("+ requestSize+ ") exceeds the configured maximum ("+ sizeMax + ")",requestSize, sizeMax); }} }public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException { DiskFileItemFactory fac = new DiskFileItemFactory(); // Make sure that the data is written to file fac.setSizeThreshold(0); if (saveDir != null) { fac.setRepository(new File(saveDir)); } // Parse the request try { ServletFileUpload upload = new ServletFileUpload(fac); upload.setSizeMax(maxSize); List items = upload.parseRequest(createRequestContext(servletRequest)); for (Object item1 : items) { FileItem item = (FileItem) item1; if (LOG.isDebugEnabled()) LOG.debug("Found item " + item.getFieldName()); if (item.isFormField()) { LOG.debug("Item is a normal form field"); List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } // note: see http://jira.opensymphony.com/browse/WW-633 // basically, in some cases the charset may be null, so // we're just going to try to "other" method (no idea if this // will work) String charset = servletRequest.getCharacterEncoding(); if (charset != null) { values.add(item.getString(charset)); } else { values.add(item.getString()); } params.put(item.getFieldName(), values); } else { LOG.debug("Item is a file upload"); // Skip file uploads that don't have a file name - meaning that no file was selected. if (item.getName() == null || item.getName().trim().length() < 1) { LOG.debug("No file has been uploaded for the field: " + item.getFieldName()); continue; } List<FileItem> values; if (files.get(item.getFieldName()) != null) { values = files.get(item.getFieldName()); } else { values = new ArrayList<FileItem>(); } values.add(item); files.put(item.getFieldName(), values); } } } catch (FileUploadException e) { LOG.error("Unable to parse request", e); errors.add(e.getMessage()); } }