SpringMVC使用FileUpload进行文件上传
导入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(); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。