使用ajax如何使用文件上传?
**
-
需要在springmvc.xml中添加配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10000000"></property> <property name="defaultEncoding" value="utf-8"></property> </bean>
-
在controller中方法
@RequestMapping(“addleave”)
@ResponseBody
public boolean addleave(HttpServletRequest request,Leave leave,MultipartFile file) {
if(!file.isEmpty()) {
String filename=UUID.randomUUID()+"_"+file.getOriginalFilename();
String realPath = request.getServletContext().getRealPath("/upload");
String path=realPath+"/"+filename;File uploadfile = new File(path);
if(!uploadfile.exists()) {
uploadfile.getParentFile().mkdirs();
}try { file.transferTo(uploadfile); HttpSession session = request.getSession(); Users attribute = (Users) session.getAttribute("users"); leave.setUid(attribute.getId()); leaveService.insertleave(leave); return true; } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return false;
}
-
在页面Ajax上传
<form id="frm" method="post" enctype="multipart/form-data" > <td align="right"><input type="file" name="file" value="附件"></td>
-
点击事件
function add(){
$.ajax({
url : '${pageContext.request.contextPath}/addleave',
type : 'POST',
cache : false,
data : new FormData($('#frm')[0]),
processData : false,
contentType : false,
dataType : "json",
success : function(data) {
if(data){
$('#center').load("${pageContext.request.contextPath}/myleave");
}else{
alert("添加失败");
}
}
});
}