【问题标题】:Serve yaml file with Spring REST endpoint使用 Spring REST 端点提供 yaml 文件
【发布时间】:2019-12-27 10:54:33
【问题描述】:

我想通过 Spring 的 REST 端点提供 .yaml 文件,我知道它不能直接显示在浏览器中(这里只讨论 Chrome),因为它不支持显示 yaml 文件。 我已经包含了我认为为此目的必要的库 compile group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-yaml', version: '2.9.9'.

如果我在浏览器中打开端点/v2/api-doc,它会提示我下载与端点/v2/api-doc 完全相同的文件。它包含正确的内容。

问:有没有办法正确传输.yaml文件,从而提示用户安全myfile.yaml?

@RequestMapping(value = "/v2/api-doc", produces = "application/x-yaml")
public ResponseEntity<String> produceApiDoc() throws IOException {
    byte[] fileBytes;
    try (InputStream in = getClass().getResourceAsStream("/restAPI/myfile.yaml")) {
        fileBytes = IOUtils.toByteArray(in);
    }
    if (fileBytes != null) {
        String data = new String(fileBytes, StandardCharsets.UTF_8);
        return new ResponseEntity<>(data, HttpStatus.OK);
    } else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

【问题讨论】:

    标签: java spring yaml


    【解决方案1】:

    您应该设置一个Content-Disposition 标头(我建议使用ResourceLoader 在Spring Framework 中加载资源)。​​

    例子:

    @RestController
    public class ApiDocResource {
    
        private final ResourceLoader resourceLoader;
    
        public ApiDocResource(ResourceLoader resourceLoader) {
            this.resourceLoader = resourceLoader;
        }
    
        @GetMapping(value = "/v2/api-doc", produces = "application/x-yaml")
        public ResponseEntity produceApiDoc() throws IOException {
            Resource resource = resourceLoader.getResource("classpath:/restAPI/myfile.yaml");
    
            if (resource.exists()) {
                return ResponseEntity
                    .ok()
                    .contentType(MediaType.parseMediaType("application/x-yaml"))
                    .header("Content-Disposition", "attachment; filename=myfile.yaml")
                    .body(new InputStreamResource(resource.getInputStream()));
            } else {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-17
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      • 1970-01-01
      • 2017-08-22
      • 2016-03-04
      • 2018-05-23
      相关资源
      最近更新 更多