ajax 提交表单(文件)

时间:2021-08-16 22:48:10

废话不多说,自己看代码

引入的jquery

<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>

表单内容

<form id="formData" enctype="multipart/form-data">
选择文件:<input type="file" name="file"/><br>
<input type="text" name="text"/><br>
<input type="button" id="sub" value="提交"/>
</form>

javascript内容

<script type="text/javascript">
$(function(){
$("#sub").bind("click",function(){
var formData = new FormData($( "#formData" )[0]);
$.ajax({
url: '${basePath}upload_b' ,
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata["errmsg"]);
},
error: function (returndata) {
alert("error!!!");
}
});
})
})

</script>

java后台接收文件

@RequestMapping("upload_b")
public @ResponseBody Map<String,Object> upload_b(HttpServletRequest req,@RequestParam(value = "file") MultipartFile file){
System.out.println(file.getOriginalFilename());
Map<String,Object> msg = new HashMap<String,Object>();
msg.put("errmsg", "文件名:"+file.getOriginalFilename()+",你输入的是:"+req.getParameter("text")+","+req.getParameter("override"));
return msg;
}