简体   繁体   中英

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. 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' .

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 . 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?

@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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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