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

x33g5p2x  于2022-03-08 转载在 Spring  
字(1.4k)|赞(0)|评价(0)|浏览(183)
@RestController
public class TestController {

    @GetMapping("/download")
    public ResponseEntity download() {
        ClassPathResource classPathResource = new ClassPathResource("application.yml");
        String filename = classPathResource.getFilename();
        HttpHeaders httpHeaders = new HttpHeaders();
  		httpHeaders.setContentDisposition(ContentDisposition.inline().filename(filename, StandardCharsets.UTF_8).build());      
  		//httpHeaders.setContentDisposition(ContentDisposition.attachment().filename(filename, StandardCharsets.UTF_8).build());
        return ResponseEntity
                .ok()
                .headers(httpHeaders)
                .body(classPathResource);
    }
}
  • inline 表示在浏览器直接展示文件内容-

  • attachment 表示下载为文件

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

ResponseEntity

ResponseEntity自定义响应体

@GetMapping("/customizeBody")
public ResponseEntity customizeBody() {
    HashMap<String, String> map = new HashMap<>();
    return ResponseEntity
            .ok()
            .body(map);
}

ResponseEntity自定义响应头

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

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

@GetMapping("/customizeHeader")
public ResponseEntity customizeHeader() {
  
    return ResponseEntity
            .status(HttpStatus.OK)
            .allow(HttpMethod.GET)
            .contentType(MediaType.APPLICATION_JSON)
            .contentLength(10240)
            .header("header","www.zysheep.cn")
            .build();
}

HttpHeaders

HttpMethod

HttpStatus

MediaType

相关文章

微信公众号

最新文章

更多