简体   繁体   English

使用 Spring REST 端点提供 yaml 文件

[英]Serve yaml file with Spring REST endpoint

I want to serve a .yaml file via a REST endpoint with Spring, I know that it cannot be directly displayed in a browser (just talking about Chrome here), since it doesn't support display of yaml files.我想通过带有 Spring 的 REST 端点提供 .yaml 文件,我知道它不能直接显示在浏览器中(这里只讨论 Chrome),因为它不支持 yaml 文件的显示。 I have included what I think is the necessary library for this purpose compile group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-yaml', version: '2.9.9' .我已经包含了我认为为此目的compile group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-yaml', version: '2.9.9'所需的库compile group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-yaml', version: '2.9.9'

If I open the endpoint /v2/api-doc in the browser, it will prompt me, to download a file named exactly as the endpoint /v2/api-doc .如果我在浏览器中打开端点/v2/api-doc ,它会提示我下载一个与端点/v2/api-doc完全相同/v2/api-doc It contains the correct content.它包含正确的内容。

Question: Is there a way to correctly transfer the .yaml file, so that the user will be prompted to safe myfile.yaml?问题:有没有办法正确传输.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);
    }
}

You should set a Content-Disposition header (and I recommend using ResourceLoader to load resources in Spring Framework).您应该设置一个Content-Disposition标头(我建议使用ResourceLoader在 Spring Framework 中加载资源)。

Example:例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM