1. 在原生Servlet中我们一般通过HttpServletResponse来实现文件的下载功能。但是使用了SpringMVC后,可以无需使用原生的方法。通过ResponseEntity即可完成。
    1. @GetMapping("download")
    2. public ResponseEntity<byte[]> download(HttpSession httpSession) throws IOException {
    3. ServletContext servletContext = httpSession.getServletContext();
    4. String filePath = servletContext.getRealPath("kobe.jpg");
    5. Path path = Paths.get(filePath);
    6. InputStream inputStream = Files.newInputStream(path);
    7. byte[] bytes = new byte[inputStream.available()];
    8. inputStream.read(bytes);
    9. //创建HttpHeaders对象设置响应头信息
    10. MultiValueMap<String, String> headers = new HttpHeaders();
    11. //设置要下载方式以及下载文件的名字
    12. headers.add("Content-Disposition", "attachment;filename=1.jpg");
    13. //设置响应状态码
    14. HttpStatus statusCode = HttpStatus.OK;
    15. ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
    16. return responseEntity;
    17. }