最近在开发过程中遇到了表单文件和内容同时传递到后台的需求,由于使用了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>
后台控制层代码如下:
@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("结束!");
}