1. public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
    2. //获取ServletContext对象
    3. ServletContext servletContext = session.getServletContext();
    4. //获取服务器中文件的真实路径
    5. String realPath = servletContext.getRealPath("/static/img/1.jpg");
    6. System.out.println(realPath);
    7. //创建输入流
    8. InputStream is = new FileInputStream(realPath);
    9. //创建字节数组
    10. byte[] bytes = new byte[is.available()];
    11. //将流读到字节数组中
    12. is.read(bytes);
    13. //创建HttpHeaders对象设置响应头信息
    14. MultiValueMap<String, String> headers = new HttpHeaders();
    15. //设置要下载方式以及下载文件的名字
    16. headers.add("Content-Disposition", "attachment;filename=1.jpg");
    17. //设置响应状态码
    18. HttpStatus statusCode = HttpStatus.OK;
    19. //创建ResponseEntity对象
    20. ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
    21. //关闭输入流
    22. is.close();
    23. return responseEntity;
    24. }