我想通过 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/