SpringMvc文件上传
pom.xml依赖
// An highlighted block
var foo = 'bar';
SpringMvc.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 文件最大大小(字节) 1024*1024*50=50M-->
<property name="maxUploadSize" value="52428800"></property>
<!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
<property name="resolveLazily" value="true"/>
</bean>
jsp页面:
<%--
Created by IntelliJ IDEA.
User: 125x
Date: 2019/11/27
Time: 10:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/book/upload" method="post" enctype="multipart/form-data" >
待上传文件:<input type="file" name="file">
<input type="submit">
</form>
</body>
</html>
java代码:
@RequestMapping("/upload")
public String upload(MultipartFile file){
System.out.println(file.getOriginalFilename());
System.out.println(file.getContentType());
try {
FileUtils.copyInputStreamToFile(file.getInputStream(),new File("E:/图片/"+file.getOriginalFilename()));
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/book/list";
}
之后运行,打上路径就OK啦!
json支持
xxxController .java
@ResponseBody
@RequestMapping("/json1")
public Map json1(HttpServletRequest req){
// ObjectMapper om=new ObjectMapper();
// String s=om.writeValueAsString("这里既可以放map,也可以放list,也可以放字符串");
PageBean pageBean=new PageBean();
pageBean.setRequest(req);
List<Map> list=bookService.listPager(new Book(),pageBean);
Map map=new HashMap();
map.put("total",101);
map.put("data",list);
return map;
}
@ResponseBody
@RequestMapping("/json2")
public List<Map> json2(HttpServletRequest req){
// ObjectMapper om=new ObjectMapper();
// String s=om.writeValueAsString("这里既可以放map,也可以放list,也可以放字符串");
PageBean pageBean=new PageBean();
pageBean.setRequest(req);
List<Map> list=bookService.listPager(new Book(),pageBean);
return list;
}
@ResponseBody
@RequestMapping("/json3")
public String json3(HttpServletRequest req){
return "SpringMvc String to json";
}
第一个返回Map集合
第二个返回list