springmvc的文件上传
程序员文章站
2022-06-03 08:55:20
...
一、springmvc的文件上传
struts文件上传
1、二进制存在数据库
2、存储到具体的硬盘目录
3、存储到服务器中
真实路径与虚拟路径
通过虚拟路径获取真实路径
request.getservletContext.getrealPath(虚拟路径);
fileutil.copyInputStreamtofile(file.getInput);
fileutil.copyofile(file,new file(真是路径))
- 添加文件上传相关依赖
<!--6、fileupload-->
<commons-fileupload.version>1.3.3</commons-fileupload.version>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
- 配置文件上传解析器(CommonsMultipartResolver)
<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>
- 表单提交方式为method=“post” enctype=“multipart/form-data”
upload.jsp
<%--
Created by IntelliJ IDEA.
User: qwf
Date: 2019/11/25
Time: 9:44
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>
-
文件项用spring提供的MultipartFile进行接收
-
IO流读写文件
-
保存文件上传记录
注:springmvc文件上传关键代码
File targetFile = …;
MultipartFile mf = …;
String fileName = mf.getOriginalFilename();
mf.transferTo(targetFile);
注意:图片的虚拟映射
测试代码:
@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:/T237_qiu/image/"+file.getOriginalFilename()));
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/book/list";
}
图片结果:
二、springmvc对json的支持
代码演示:
map、list、String类型
@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) {
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";
}
图片结果: