1.文件下载
使用ResponseEntity实现下载文件的功能
@GetMapping("/testDown")
public ResponseEntity<byte[]> testResponseEntity(String filePath) throws IOException {
String suffix = filePath.substring(filePath.lastIndexOf('.')); //获取文件后缀
String fileName = UUID.randomUUID().toString()+suffix; //文件名 = uuid+文件后缀
//创建输入流
InputStream is = new FileInputStream(filePath);
//创建字节数组
byte[] bytes = new byte[is.available()];
//将流读到字节数组中
is.read(bytes);
//创建HttpHeaders对象设置响应头信息
MultiValueMap<String, String> headers = new HttpHeaders();
//设置要下载方式以及下载文件的名字, 只有filename="xxx"可以自定义, "Content-Disposition", "attachment;"是固定写法
headers.add("Content-Disposition", "attachment;filename="+fileName);
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(bytes, headers, statusCode);
//关闭输入流
is.close();
return responseEntity;
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>hello world!</h1>
<form th:action="@{/testDown}" method="get">
文件路径:<input type="text" name="filePath"><br>
<input type="submit" value="下载">
</form>
</body>
</html>
运行测试
下载net.zip
输入文件路径
下载完成
2.文件上传
文件上传要求form表单的请求方式必须为post,并且添加属性enctype=“multipart/form-data”
SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息。
上传步骤
1.添加依赖:
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<!--文件上传依赖, 文件下载不需要这个-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2.在SpringMVC的配置文件中添加配置:
<!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
3.控制器方法:
@PostMapping("/testUp")
public String testUp(MultipartFile file) throws IOException {
//获取上传的文件的文件名
String fileName = file.getOriginalFilename();
//处理文件重名问题
String suffix = fileName.substring(fileName.lastIndexOf("."));
fileName = UUID.randomUUID().toString() + suffix;
//图片存储文件夹路径, 请替换成你电脑下存在的文件夹路径
String dir = "E:\\Office文档\\tu\\file\\upload";
String finalPath = dir + File.separator + fileName;
//实现上传功能
file.transferTo(new File(finalPath));
return "success";
}
4.前端页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>hello world!</h1>
<form th:action="@{/testUp}" method="post" enctype="multipart/form-data">
图片:<input type="file" name="file"><br>
<input type="submit" value="上传">
</form>
</body>
</html>
5.运行测试
上传boot.png
上传成功