最近在开发过程中遇到了表单文件和内容同时传递到后台的需求,由于使用了shiro框架,在后台接收的时候会遇到了类型转换的错误。尝试了很多解决办法,还好最终解决了。这里记录一下。 首先是前台代码: <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <jsp:include page="/static/header.jsp"/> </head> <body> <form id= "uploadForm" enctype="multipart/form-data"> <p >指定文件名: <input type="text" name="filename" value= ""/></p > <p >上传文件: <input type="file" name="file"/></ p> <input type="button" value="上传" onclick="doUpload()" /> </form> <jsp:include page="/static/footer.jsp"/> <script type="text/javascript"> function getRequestUrl() { var strFullPath = window.document.location.href; var strPath = window.document.location.pathname; var pos = strFullPath.indexOf(strPath); var prePath = strFullPath.substring(0, pos); var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1); var path = prePath + postPath; return path; } function doUpload() { var formData = new FormData($( "#uploadForm" )[0]); formData.append("CODE","123456"); //自定义参数传递 $.ajax({ url: getRequestUrl() + "/testUpLoadForm", type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function (data) { alert(data); }, error: function (data) { alert(data); } }); } </script> </body> </html> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 后台控制层代码如下: @RequestMapping("/testUpLoadForm") public void testUpLoadForm(HttpServletRequest request){ //因为使用的shiro框架,因此这里传递过来的类型需要转换一下 ShiroHttpServletRequest shiroRequest = (ShiroHttpServletRequest) request; CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(); MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest) shiroRequest.getRequest()); Iterator<String> itr = multipartRequest.getFileNames(); MultipartFile multipartFile = null; while (itr.hasNext()) { multipartFile = multipartRequest.getFile(itr.next()); String fileRealName1 = multipartFile.getName(); String fileRealName = multipartFile.getOriginalFilename(); System.out.println(fileRealName1); System.out.println(fileRealName); } String sName = multipartRequest.getParameter("filename"); System.out.println("结束!"); } |
Archiver|知识站 ( 鲁ICP备20004068号-1 )
GMT+8, 2020-6-23 22:50 , Processed in 0.017336 second(s), 17 queries .