SpringMVC - (11) 文件下载功能实现
1. 文件下载
文件下载:将服务器的资源下载到本地
使用ResponseEntity实现下载文件的功能,ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文
2. 具体实现
2.1 编写下载页面,提供下载链接
file_download.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>下载页面</title>
</head>
<body>
<h1>文件下载</h1>
<a th:href="@{/file/download}">点此链接下载图片</a>
</body>
</html>
在控制器中配置请求映射
@RequestMapping("/file_down")
public String fileDownload(){
return "file_download";
}
2.2 编写控制器方法
@Controller
@RequestMapping("/file")
public class FileController {
@RequestMapping("/download")
public ResponseEntity<byte[]> fileDownload(HttpSession session) throws IOException {
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//获取服务器中文件的真实路径
String realPath = servletContext.getRealPath("/static/imgs/05.png");
//创建输入流
InputStream is = new FileInputStream(realPath);
//创建字节数组
byte[] bytes = new byte[is.available()];
//将流读到字节数组中
is.read(bytes);
//创建HttpHeaders对象设置响应头信息
MultiValueMap<String, String> headers = new HttpHeaders();
//设置要下载方式以及下载文件的名字
headers.add("Content-Disposition", "attachment;filename=05.png");
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
//关闭输入流
is.close();
return responseEntity;
}
}
2.3 测试功能
浏览器访问http://localhost:8080/springMVC/file_down
点击链接下载:
可以将文件下载到本地