使用ResponseEntity实现下载文件的功能
    (语法固定只需要改文件名称)

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