spring版本:5.0.2
spring-mvc.xml配置:
在
<mvc:annotation-driven/>
后加上
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
web.xml配置
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!-- 这里开始是文件上传的配置-->
<load-on-startup>1</load-on-startup>
<multipart-config>
<location>d:/share/</location>
<max-file-size>4097152</max-file-size>
<max-request-size>8194304</max-request-size>
</multipart-config>
<!-- 到这里结束-->
</servlet>
HTML:
<input type="file" id="file" />
jq:
var formData = new FormData();
var files = $("#file")[0].files[0];
formData.append("file", files);
$.ajax({
url: "你的url",
type: "post",
data: formData,
cache: false,
processData: false,
contentType: false,
success: function (data) {
成功后执行的方法
}
}
);
formData内还可以放其他变量如
formData.append("user_id", 1);
formData.append("names", "张三");
formData.append("telephone", "12345678901");
formData.append("email", "123@123.com");
后台接收
@RequestMapping(value = "/client/updateUser", method = RequestMethod.POST)
@ResponseBody
public ServiceResponse updateUser(@RequestParam(value = "file",required = false)MultipartFile file/*如果加了其他参数可以在这后面加一个对象接收*/) throws IOException {
}