进口FileUpload和common-io的Jar包
注意:1、Struts2其它方法需要使用的:struts2过滤,将改变reqeust类型,由HttpServletRequest成为MultiPartRequestWrapper
1、Test.jsp:
<form action="<%=basePath%>self/testFileUpload.do" method="post" enctype="multipart/form-data"> <input type="text" name="num"> <input name="img1" type="file" accept="image/gif,image/jpg,image/png,image/jpeg"/> <input name="img2" type="file" accept="image/gif,image/jpg,image/png,image/jpeg"/> <input type="submit" name="test"> <input type="reset" name="test1"> </form>
2、controller:
@RequestMapping(value="/testFileUpload") public void testFileUpload(HttpServletRequest request,HttpServletResponse response) throws Exception{ String num = ""; String img1 = ""; String img2 = ""; String fileName = ""; try { String t = request.getCharacterEncoding(); boolean isMultipart = ServletFileUpload.isMultipartContent(request);//推断是否是表单文件类型 if(isMultipart){ DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(request.getCharacterEncoding());//这里非常重要啊 解决linux环境下上传文件名称乱码的问题 //upload.setFileSizeMax(3*1024*1024);//3M List items = upload.parseRequest(request); if(items.size() == 0){ System.out.println("无数据"); } Iterator<Object> formItem = items.iterator(); while(formItem.hasNext()){ FileItem item = (FileItem) formItem.next(); //假设是表单元素 if(item.isFormField()){ if (item.getFieldName().equals("num")) { num = item.getString(request.getCharacterEncoding()).trim(); } } //假设不是表单元素 if(!item.isFormField()){ String name = item.getName(); String type = item.getContentType(); long sizeInBytes = item.getSize(); try { String fullName = item.getName().trim(); if(fullName != ""){ fileName = System.currentTimeMillis() + fullName.substring(fullName.indexOf(".")); if(item.getFieldName().equals("img1")){ fileName = "img1-" + System.currentTimeMillis() + fullName.substring(fullName.indexOf(".")); } if(item.getFieldName().equals("img2")){ fileName = "img2-" + System.currentTimeMillis() + fullName.substring(fullName.indexOf(".")); } String tomcatRoot = FileOperator.getRootPath(); String path = tomcatRoot; if(FileOperator.FileUploadEx(path, fileName, item.getSize(), item.getInputStream())){ if(item.getFieldName().equals("img1")){ System.out.println("testimg1"); } if(item.getFieldName().equals("img2")){ System.out.println("testimg2"); } } } } catch (Exception e) { e.printStackTrace(); } } } }else{ System.out.println("非multipart/form-data提交方式"); } } catch (Exception e) { e.printStackTrace(); } }
版权声明:本文博客原创文章,博客,未经同意,不得转载。
本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/4634845.html,如需转载请自行联系原作者