SpringMVC + Ajax文件上传
前端
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>ajax文件上传练习</title> <script type="text/JavaScript" src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js"></script> </head> <script type="text/javascript"> $(function () { $("input[type='button']").click(function () { var formData = new FormData($("#upForm")[0]); $.ajax({ type: "post", url: "${pageContext.request.contextPath}/upfile/upload", data: formData, cache: false, processData: false, contentType: false, success: function (data) { alert(data); }, error: function (response) { console.log(response); alert("上传失败"); } }); }); }); </script> <body> <form id="upForm" method="post" enctype="multipart/form-data"> 用户名:<input type="text" name="userName" id="userName" /><br/> 密码:<input type="password" name="pwd" id="pwd" /><br/> <input type="file" name="image"><br/> <input type="button" value="提交" /> </form> </body> </html>
注意:
14行的 data 别打成 date ;(手贱打错,折腾半天)
后台的Controller
@Controller @RequestMapping("/upfile") public class UpFileController { @RequestMapping("/upload") @ResponseBody public String getMsg(UserTest user,@RequestParam("image") CommonsMultipartFile file){ System.out.println(user.getUserName()); System.out.println(file.getOriginalFilename()); return "接收成功"; } }
注意:第6行注解里的 image 必须和 文件控件的name属性保持一致
<input type="file" name="image">
@RequestParam("image")
SpringMVC的配置文件
<!-- 定义文件上传解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding"> <value>UTF-8</value> </property> <property name="maxUploadSize"> <value>32505856</value><!-- 上传文件大小限制为31M,31*1024*1024 --> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean>
容易出现的错误
1.访问后台成功,回来前端时404或是没有信息返回
原因:Controller没有加@ResponseBody 注解
2.前端提交信息,没有到Controller,前端报错400
Failed to load resource: the server responded with a status of 400 (Bad Request)
就是这个bug,折腾我一下午,痛苦。
原因:参数不匹配