java - 使用 Spring REST 端点提供 yaml 文件

标签 java spring yaml

我想通过 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);
    }
}

最佳答案

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

示例:

@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);
        }
    }
}

关于java - 使用 Spring REST 端点提供 yaml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57603856/

相关文章:

java - 为intelliJ设置JAVA_HOME?

java - 在 Java 中使用正则表达式从字符串中提取值

python - 如何将 python 列表转换为简单的 YAML?

java - 如何使用默认值初始化数据库

docker-compose - 在ansible中创建一个带有循环的docker-compose

Go YAML 解析器默默地失败

java - java中的ArrayList错误(无法使两个数字相等)

java - 连接关闭时 Activity 事务的行为?

java - 为什么我的 Spring Controller 不处理 GraphiQL 发送的 OPTIONS 请求?

java - Spring 4 带有 Java Config,没有 xml