1、 使用 ResponseEntity 相应实体进行返回文件
@RequestMapping("/testDown")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
// 获取 ServletContext 对象,用于获取服务器中文件真实路径
ServletContext servletContext = session.getServletContext();
// 构建文件真实路径
String realPath = servletContext.getRealPath("/static/img/319d808740c84c4ca1e318b24e7e88ca.jpg");
// 创建输出流
InputStream is = new FileInputStream(realPath);
// 创建文件字节大小的数组
// is.available() 文件字节大小
byte[] bytes = new byte[is.available()];
// 将流读到字节数组中
is.read(bytes);
// 创建HttpHeaders 对象设置响应头信息
MultiValueMap<String,String> headers = new HttpHeaders();
// 设置要下载的方式以及下载文件的名字
headers.add("Content-Disposition","attachment;filename=123.jpg");
// 设置相应状态码
HttpStatus httpStatus = HttpStatus.OK;
// 创建RepsonseEntity对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes,headers,httpStatus);
// 关闭输入流
is.close();
return responseEntity;
}
2、 使用 servlet getOutputStream() 方法对字节流进行输出
@RequestMapping("/testDown2")
public void test(HttpServletResponse resp,HttpSession session) throws IOException {
ServletContext httpContext = session.getServletContext();
String realPath = httpContext.getRealPath("/static/img/319d808740c84c4ca1e318b24e7e88ca.jpg");
InputStream inputStream = new FileInputStream(realPath);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
resp.setHeader("Content-Disposition","attachment;filename=123.jpg");
resp.getOutputStream().write(bytes);
inputStream.close();
}