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,折腾我一下午,痛苦。
原因:参数不匹配
就是前面的两个注意,data别打错,还有文件控件的name属性要和后台Controller 方法的@RequestParam参数一致
相关推荐
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
lyqdanang 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19
83510998 2020-07-18
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07
李永毅 2020-07-05
坚持着执着 2020-07-05