# 9.SpringMVC-文件上传和下载
# 1.文件下载
使用ResponseEntity实现下载文件的功能
@RequestMapping("/testDown")
public ResponseEntity<byte[]> testDown(HttpSession session) throws IOException {
//获取servletContext对象
ServletContext context = session.getServletContext();
//获取真实路径
String realPath = context.getRealPath("/static/img/1.png");
//创建输入流
FileInputStream is = new FileInputStream(realPath);
//创建数组,数组长度为文件输入流长度
byte[] bytes = new byte[is.available()];
//将流读到字节数组中
is.read(bytes);
//创建HttpHeader对象获取响应流
MultiValueMap<String,String> headers = new HttpHeaders();
//设置要下载方式以及下载文件的名字
headers.add("Content-Disposition","attachment;filename=1.png");
//设置状态码
HttpStatus ok = HttpStatus.OK;
//创建ResponseEntity对象返回
ResponseEntity<byte[]> entity = new ResponseEntity<>(bytes, headers, ok);
is.close();
return entity;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 2、文件上传
文件上传要求form表单的请求方式必须为post,并且添加属性enctype=“multipart/form-data”
SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息
上传步骤:
a>添加依赖:
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
1
2
3
4
5
6
2
3
4
5
6
b>在SpringMVC的配置文件中添加配置:
<!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
1
2
2
c>控制器方法:
@RequestMapping("/testUp")
public String testUp(HttpSession session, MultipartFile photo) throws IOException {
ServletContext context = session.getServletContext();
String realPath = context.getRealPath("photo");
//判断是否有文件目录,没有就创建
File file = new File(realPath);
if (!file.exists()){
file.mkdir();
}
//获取原始文件名
String filename = photo.getOriginalFilename();
//获取前缀
String suffix = filename.substring(filename.lastIndexOf("."));
//获取不重复的文件名
filename= UUID.randomUUID().toString()+suffix;
String finalPath=realPath+File.separator+filename;
//实现上传功能
photo.transferTo(new File(finalPath));
return "success";
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20