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