SpringMVC 使用ResponseEntity封装结果集进行文件下载

x33g5p2x  于2022-03-08 转载在 Spring  
字(1.4k)|赞(0)|评价(0)|浏览(242)
  1. @RestController
  2. public class TestController {
  3. @GetMapping("/download")
  4. public ResponseEntity download() {
  5. ClassPathResource classPathResource = new ClassPathResource("application.yml");
  6. String filename = classPathResource.getFilename();
  7. HttpHeaders httpHeaders = new HttpHeaders();
  8. httpHeaders.setContentDisposition(ContentDisposition.inline().filename(filename, StandardCharsets.UTF_8).build());
  9. //httpHeaders.setContentDisposition(ContentDisposition.attachment().filename(filename, StandardCharsets.UTF_8).build());
  10. return ResponseEntity
  11. .ok()
  12. .headers(httpHeaders)
  13. .body(classPathResource);
  14. }
  15. }
  • inline 表示在浏览器直接展示文件内容-

  • attachment 表示下载为文件

Spring 提供关于http请求相关的类

ResponseEntity

ResponseEntity自定义响应体

  1. @GetMapping("/customizeBody")
  2. public ResponseEntity customizeBody() {
  3. HashMap<String, String> map = new HashMap<>();
  4. return ResponseEntity
  5. .ok()
  6. .body(map);
  7. }

ResponseEntity自定义响应头

在SpringMVC 中我们一般使用@RequestMapping 注解的属性指定响应头:
value:指定请求的实际的地址,指定的地址可以是 URI Template 模式;
method:指定访问的方法
consumes:指定处理请求的内容类型,比如 aplication/json;text/html
produces:指定返回的内容的类型
params:指定 request 中必须包含某些参数值时,才让该方法处理请求
headers:指定 request 中必须包含指定的 header 值,才能让该方法处理请求

也可以使用ResponseEntity自定义响应头

  1. @GetMapping("/customizeHeader")
  2. public ResponseEntity customizeHeader() {
  3. return ResponseEntity
  4. .status(HttpStatus.OK)
  5. .allow(HttpMethod.GET)
  6. .contentType(MediaType.APPLICATION_JSON)
  7. .contentLength(10240)
  8. .header("header","www.zysheep.cn")
  9. .build();
  10. }

HttpHeaders

HttpMethod

HttpStatus

MediaType

相关文章