文件上传
回顾之前学过的struts文件上传,与springmvc文件上传相似
struts
- 上传界面
form多功能表单enctype=“mutipart/form-data” method=“post” - UploadFileAction
File file
String fileFileName
String fileContentType - 完成图片的虚拟映射
- 为了开发便捷,需要引入common-fileUpload
FileUtil.copy(source,target)
springmvc文件上传
- 上传界面
form多功能表单enctype=“mutipart/form-data” method=“post” - @requestMapping("/upload")
MutipartFile file - 完成图片的虚拟映射
- 为了开发便捷,需要引入common-fileUpload
FileUtil.copyinputStreamtoFile(inputStream,target)
代码展示:
- 在BookController.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("D:/Other/"+file.getOriginalFilename()));
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/book/list";
}
- 写一个jsp页面
upload.jsp
<%--
Created by IntelliJ IDEA.
User: ld
Date: 2019/11/24
Time: 17:14
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>
- 添加文件上传的pom 依赖
<commons-fileupload.version>1.3.3</commons-fileupload.version>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
- 在xml中添加配置(springmvc-servlet.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>
- 展示效果
json
HelloController.java
//map集合里面套了list
@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;
}
//直接是list
@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
只有list
字符串